'use strict';
define(function() {
  var GroupsCtrl = function(
    $scope,
    GroupsFactory,
    RolesFactory,
    $rootScope,
    gaDomUtils
  ) {
    // Edit Groups Tabs
    $scope.tabs = [
      {
        title: 'common.general',
        content: 'js/XG/modules/rights/views/modals/modal.groups_general.html',
      },
      {
        title: 'rights.roles.title',
        content: 'js/XG/modules/rights/views/modals/modal.groups_roles.html',
      },
    ];
    $scope.tabs.activeTab = 0;

    /*
         Dual list box configuration
         */
    $scope.$on('data_modal', function() {
      $scope.tabs.activeTab = 0;

      // create calendar roles
      if (
        $rootScope.xgos.portal.parameters &&
        $rootScope.xgos.portal.parameters.calendar
      ) {
        $scope.createCalendarRoles = { manager: false, consult: false };
      }

      console.log('test');
      // Roles DualListBox
      $scope.dLBRolesData = {
        leftData: angular.copy($scope.edit_resource.roles),
        leftDisplayAttribute: 'name',
        rightData: angular.copy(RolesFactory.resources.rolesLight),
        rightDisplayAttribute: 'name',
        leftTitle: 'rights.users.roles',
        rightTitle: 'rights.roles.title',
        source: 'right',
      };
    });

    /**
     * Create or update a Group
     */
    $scope.editGroup = function() {
      gaDomUtils.showGlobalLoader();
      $scope.edit_resource.roles = $scope.dLBRolesData.leftData;

      if ($scope.isNewResource) {
        GroupsFactory.add($scope.edit_resource)
          .then(function() {
            $scope.isNewResource = false;
          }).finally( () => {
            if (
              !$scope.createCalendarRoles ||
              (!$scope.createCalendarRoles.manager &&
              !$scope.createCalendarRoles.consult)) {
                gaDomUtils.hideGlobalLoaderAfterTimeout();
            }
          });
      } else {
        GroupsFactory.update($scope.edit_resource)
          .finally( () => {
            if (
              !$scope.createCalendarRoles ||
              (!$scope.createCalendarRoles.manager &&
              !$scope.createCalendarRoles.consult)) {
                gaDomUtils.hideGlobalLoaderAfterTimeout();
            }
          });
      }

      if ($scope.createCalendarRoles && $scope.createCalendarRoles.manager) {
        RolesFactory.add({
            name: 'kis_calendar_manager_' + $scope.edit_resource.name,
            authorizations: [],
          }).finally(gaDomUtils.hideGlobalLoaderAfterTimeout);
      }
      if ($scope.createCalendarRoles && $scope.createCalendarRoles.consult) {
        RolesFactory.add({
            name: 'kis_calendar_consult_' + $scope.edit_resource.name,
            authorizations: [],
          }).finally(gaDomUtils.hideGlobalLoaderAfterTimeout);
      }
    };

    /**
     *
     */
    $scope.roleExisteDeja = function(role) {
      var res = false;
      RolesFactory.resources.rolesLight.map(function(xd) {
        if (xd.name == role + $scope.edit_resource.name) {
          res = true;
        }
      });
      return res;
    };

    /**
     * Group removal
     */
    $scope.removeGroup = function() {
      GroupsFactory.remove($scope.edit_resource.uid).then(function() {
        //$scope.tableParams.total($scope.currentResources.length).reload();
      });
    };

    /**
     * Groups loading
     * Also loads Roles if not previously loaded
     */
    $scope.currentResources = GroupsFactory.resources.groupsLight;

    if (GroupsFactory.resources.groupsLight.length == 0) {
      if (RolesFactory.resources.rolesLight.length == 0) RolesFactory.get(true);

      GroupsFactory.get(true).then(function() {
        $scope.currentResources = GroupsFactory.resources.groupsLight;
      });
    }

    /**
         EditList Directive configuration
         */
    $scope.editListCfg = {
      dataModule: 'rights',
      resource_type: 'groups',
      cols: ['name', 'uid'],
      removeFunction: $scope.removeGroup,
    };

    $scope.validForm = {};
    $scope.validateName = function() {
      var actualName = $scope.edit_resource.name;
      $scope.$watch(
        'edit_resource.name',
        function(name) {
          $scope.nameExists =
            $scope.currentResources
              .map(function(r) {
                return r.name;
              })
              .indexOf(name) != -1;
          if (!$scope.isNewResource && $scope.edit_resource.name == actualName)
            $scope.nameExists = false;
          $scope.validForm.name = !$scope.nameExists;
        },
        1
      );
    };
  };

  GroupsCtrl.$inject = [
    '$scope',
    'GroupsFactory',
    'RolesFactory',
    '$rootScope',
    'gaDomUtils',
  ];
  return GroupsCtrl;
});
