backupApp.directive('backupNotificationForm', function (gettextCatalog) {
  return {
    restrict: 'E',
    scope: {
      alert: '=',
      validationCallback: '='
    },
    templateUrl: 'templates/backupNotificationForm.html',
    controller: function ($scope, AppService, AppUtils, SystemInfo, EditUriBackendConfig, DialogService, EditUriBuiltins) {
      $scope.Levels = [{ label: 'Success' }, { label: 'Warning' }, { label: 'Error' }, { label: 'Fatal' }]
      for (const level of $scope.Levels) {
        level.checked = $scope.alert.TriggerLevels.find(l => l == level.label) !== undefined
      }
      $scope.AllLevelsChecked = false

      function changeSeletedTriggerLevels() {
        $scope.alert.TriggerLevels = $scope.Levels.filter(l => l.checked === true).map(l => l.label);
        validateInputs();
      }

      $scope.CheckIfAllSelected = function () {
        $scope.AllLevelsChecked = $scope.Levels.filter(l => l.checked === true).length === $scope.Levels.length
        changeSeletedTriggerLevels();
      }

      $scope.SelectRemoveAll = function () {
        for (const level of $scope.Levels) {
          level.checked = $scope.AllLevelsChecked
        }
        changeSeletedTriggerLevels();
      }

      function validateInputs() {
        function validateEmail(email) {
          return email.match(
            /^\S+@\S+\.\S+$/
          ) != null;
        };

        $scope.emailIsValid = validateEmail($scope.alert.Recipient);
        $scope.levelIsValid = $scope.alert.TriggerLevels.length > 0;

        $scope.alert.isValid = $scope.emailIsValid && $scope.levelIsValid;
        if ($scope.validationCallback) {
          $scope.validationCallback();
        }
      }

      $scope.$watch('alert.Recipient', validateInputs);
      $scope.$watchCollection('Levels', $scope.CheckIfAllSelected);
    }
  }
})