/////////////////////////////////////////////////////////////
// Gestion de la configuration des règles métiers.
/////////////////////////////////////////////////////////////
'use strict';
define(function() {
  var gcelement = function (ngTableParams, ngDialog, $filter, $timeout) {
    return {
      templateUrl:
        'js/XG/modules/model/views/directives/featuretypeActions.html',
      restrict: 'E',
      scope: {
        currentfeaturetype: '=featuretype',
      },
      link: function(scope) {
        if (angular.isUndefined(scope.currentfeaturetype.actions))
          scope.currentfeaturetype.actions = [];

        /**
         * Paramètres du tableau listant les règles associées au currentfeaturetype passé à cette directive
         */
        scope.tableParams = new ngTableParams(
          {
            page: 1, // show first page
            count: 10, // count per page
          },
          {
            total: 0, // length of data
            getData: function($defer, params) {
              var displayedTab = scope.currentfeaturetype.actions.slice(
                (params.page() - 1) * params.count(),
                params.page() * params.count()
              );

              params.total(scope.currentfeaturetype.actions.length); // set total for recalc pagination
              $defer.resolve(displayedTab);
            },
          }
        );

        scope.actionsOptions = [
          $filter('translate')('model.featuretypes.actions.form'),
          $filter('translate')('model.featuretypes.actions.jasper'),
          $filter('translate')('model.featuretypes.actions.url'),
          $filter('translate')('model.featuretypes.actions.esrigeoprocess'),
          $filter('translate')('model.featuretypes.actions.html'),
          $filter('translate')('model.featuretypes.actions.majic'),
          $filter('translate')('model.featuretypes.actions.dossier_anc'),
          $filter('translate')('model.featuretypes.actions.widget'),


          // Version initiale pour gérer les détails d'intervention pour le CD93.
          // Remplacer par un formulaire standard du formbuilder
            // Le code associé à cette action n'est pas commenté,
            // il sera à supprimer si cette action 'is_detail' est supprimée
          // $filter('translate')('model.featuretypes.actions.is_detail'),
        ];

        if (scope.currentfeaturetype.name === 'AEP_ANOMALIE')
          scope.actionsOptions.push(
            $filter('translate')('model.featuretypes.actions.anomalie')
          );

        /**
         * Ouvre la popup d'ajout d'une régle
         * @returns {undefined}
         */

        scope.addNewAction = function() {
          scope.editMode = 'add';
          scope.currentEditedAction = {
            id: Math.floor(Math.random() * 10000),
          };
          scope.allActionsNames = scope.currentfeaturetype.actions.map(
            function (x) {
            return x.name;
          });
          scope.dialogProperties = ngDialog.open({
            template:
              'js/XG/modules/model/views/modals/modal.featuretypes.actions.html',
            scope: scope,
            closeByDocument: false,
            className: 'ngdialog-theme-plain width1200',
            preCloseCallback: scope.closePropertiesDialog,
          });
        };

        scope.onDropg2c = function(target, source) {
          target = fixIndexCaseManyPages(target);
          index = fixIndexCaseManyPages(source == '' ? 0 : source);
          let actionragged = scope.currentfeaturetype.actions[index];
          scope.currentfeaturetype.actions.splice(index, 1);
          scope.currentfeaturetype.actions.splice(target, 0, actionragged);
          scope.tableParams.reload();
        };

        /**
         * Ouvre la popup d'ajout d'une régle avec la règle en cours 'rule'
         * @param rule la règle correspondante au bouton cliqué dans le tableau des règles enregistrées pour ce featureType.
         * @returns {undefined}
         */

        scope.updateAction = function(action) {
          scope.editMode = 'update';
          scope.currentEditedAction = angular.copy(action);
          scope.allActionsNames = scope.currentfeaturetype.actions.map(
            function (x) {
            return x.name;
          });
          scope.dialogProperties = ngDialog.open({
            template:
              'js/XG/modules/model/views/modals/modal.featuretypes.actions.html',
            scope: scope,
            closeByDocument: false,
            className: 'ngdialog-theme-plain width1200',
            preCloseCallback: scope.closePropertiesDialog,
          });
        };

        /**
         * Supprime du tableau des règles du featureType, toutes celles sélectionnées.
         * @returns {undefined}
         */
        scope.removeActionFromFeatureType = function() {
          var tr = confirm(
            $filter('translate')(
              'model.featuretypes.actions.confirmSuppression'
            )
          );
          if (tr) {
            var newRulesTab = [];
            for (var i = 0; i < scope.currentfeaturetype.actions.length; i++) {
              if (!scope.currentfeaturetype.actions[i].$selected) {
                newRulesTab.push(scope.currentfeaturetype.actions[i]);
              } else {
                if (scope.currentfeaturetype.actions[i].defaultAction)
                  scope.currentfeaturetype.defaultsAction = null;
              }
            }
            scope.currentfeaturetype.actions = newRulesTab;
            scope.tableParams.reload();
          }
        };

        scope.actionMoveDown = (idx) => {
          idx = fixIndexCaseManyPages(idx);
          if (idx !== -1) {
            let rule = scope.currentfeaturetype.actions[idx];
            rule.$selected = false;
            scope.currentfeaturetype.actions.splice(idx, 1);
            scope.currentfeaturetype.actions.splice(idx + 1, 0, rule);
          }
          scope.tableParams.reload();
        };

        scope.actionMoveUp = (idx) => {
          idx = fixIndexCaseManyPages(idx);
          if (idx !== -1) {
            let rule = scope.currentfeaturetype.actions[idx];
            rule.$selected = false;
            scope.currentfeaturetype.actions.splice(idx, 1);
            scope.currentfeaturetype.actions.splice(idx - 1, 0, rule);
          }
          scope.tableParams.reload();
        };

        scope.atLeastOneSelectedAction = false;
        scope.selectAction = (idx) => {
          idx = fixIndexCaseManyPages(idx);
          scope.currentfeaturetype.actions.map((x, i) => {
            if (i === idx) {
              x.$selected = !x.$selected;
              x.$selected
                ? (scope.atLeastOneSelectedAction = true)
                : (scope.atLeastOneSelectedAction = false);
            } else {
              x.$selected = false;
            }
          });
        };

        scope.disableActionMove = (idx, type) => {
          idx = fixIndexCaseManyPages(idx);
          return type === 'up'?idx === 0:
                                    idx === scope.tableParams.total()-1;
        }

        let fixIndexCaseManyPages = (idx) => {
          if(scope.tableParams && idx != -1){
            return (scope.tableParams.page() - 1) * scope.tableParams.count() +idx;
          }else{
            return idx;
          }
        }

        scope.closePropertiesDialog = function() {
          scope.tableParams.reload();
        };

        scope.addActionToFeatureType = function(currentEditedAction) {
          switch (scope.editMode) {
            case 'add':
              scope.currentfeaturetype.actions.push(currentEditedAction);
              break;
            case 'update':
              for (
                var i = 0;
                i < scope.currentfeaturetype.actions.length;
                i++
              ) {
                if (
                  scope.currentfeaturetype.actions[i].id ===
                  currentEditedAction.id
                ) {
                  scope.currentfeaturetype.actions[i] = currentEditedAction;
                  if (currentEditedAction.defaultAction) {
                    if (
                      (currentEditedAction.actionType ===
                        $filter('translate')(
                          'model.featuretypes.actions.jasper'
                        ) ||
                        currentEditedAction.typeInfo === 'JASPER') &&
                      currentEditedAction.currentComponent
                    ) {
                      currentEditedAction.currentComponent = false;
                    }
                    scope.currentfeaturetype.defaultsAction = currentEditedAction;
                  }
                  break;
                }
              }
              break;
          }
          scope.tableParams.reload();
          return true;
        };

        scope.setDefaultAction = function(action) {
          if (!action.defaultAction) {
            scope.currentfeaturetype.defaultsAction = null;
          } else {
            scope.currentfeaturetype.actions.map(function(a) {
              if (a.id !== action.id) {
                a.defaultAction = false;
              } else if (
                a.id === action.id &&
                action.actionType ===
                  $filter('translate')('model.featuretypes.actions.jasper') &&
                action.currentComponent
              ) {
                action.currentComponent = false;
                a.currentComponent = false;
              }
            });
            scope.currentfeaturetype.defaultsAction = action;
          }
        };
        scope.openActionRole = (action) => {
          let hasConfirmed = false;
          prepareRoles(action);
          ngDialog.open({
            template:
                'js/XG/modules/model/views/modals/modal.featuretypes.actions.role.html',
            scope: scope,
            closeByDocument: false,
            className: 'ngdialog-theme-plain width400 miniclose',
            preCloseCallback: () =>{
              if (!hasConfirmed && scope.tempRoles && scope.tempRoles.roles){
                $timeout(()=>{
                  action.roles = scope.tempRoles.roles.join(', ');
                  scope.tempRoles = {};
                }, 300);
              }
              hasConfirmed = true;
            },
          });
        };
        const prepareRoles = (action) => {
          scope.tempRoles = {};
          if (action && action.roles && action.roles.length > 0){
            scope.tempRoles.roles = [];
            scope.tempRoles.roles = action.roles.split(', ');
          }
        };
      },
    };
  };

  gcelement.$inject = ['ngTableParams', 'ngDialog', '$filter', '$timeout'];
  return gcelement;
});
