/**
 *
 */
'use strict';
define(function() {
  /**
   * Portals Ctrl
   * @param $scope
   * @param $rootScope
   * @param $window
   * @param $translate
   * @param $filter
   * @param PortalsFactory
   * @constructor
   * @param DataStoreFactory
   * @param gaDomUtils
   * @param CalendarFactory
   * @param $timeout
   * @param gaJsUtils
   * @param ElasticFactory
   * @param ngDialog
   * @param ThemesFactory
   * @param RolesFactory
   */
  var PortalsCtrl = function(
    $scope,
    $rootScope,
    $window,
    $filter,
    PortalsFactory,
    OmegaFactory,
    DataStoreFactory,
    gaDomUtils,
    CalendarFactory,
    $timeout,
    gaJsUtils,
    ElasticFactory,
    ngDialog,
    ThemesFactory,
    RolesFactory,
    RegionalFactory,
    PcwinFactory
  ) {
    // -- Gestionnaire de messages de type toast
    const toastr = require('toastr');
    // -- Option pour les toastr des messages de suppression
    const toastrOptions = {
      positionClass: 'toast-portals',
      timeOut: 20000
    };

    /*
     * Available themes
     */
    if (angular.isUndefined($scope.themes)) {
      $scope.themes = [
        {
          file: 'default',
          label: $filter('translate')('portals.theme.default_style'),
        },
        {
          file: 'dark',
          label: $filter('translate')('portals.theme.dark_style'),
        },
        {
          file: 'green',
          label: $filter('translate')('portals.theme.green_style'),
        },
        {
          file: 'pink',
          label: $filter('translate')('portals.theme.pink_style'),
        },
        {
          file: 'rose',
          label: $filter('translate')('portals.theme.rose_style'),
        },
      ];
    }

    // console.log($scope.themes);

    /**
     * Available api
     */

    $scope.cfg = {};
    $scope.cfg.sendMailServerType = '';

    $scope.defineTabs = function() {
      $scope.tabs = [
        {
          title: 'portals.mainDB.title',
          content: 'js/XG/modules/portals/views/modals/modal.mainDB.html',
        },
        {
          title: 'portals.sendmail.title',
          content: 'js/XG/modules/portals/views/modals/modal.sendmail.html',
        },
        {
          title: 'portals.tracker.title',
          content: 'js/XG/modules/portals/views/modals/modal.tracker.html',
        },
        {
          title: 'portals.history.title',
          content: 'js/XG/modules/portals/views/modals/modal.history.html',
        },
        {
          title: 'portals.calendar.title',
          content: 'js/XG/modules/portals/views/modals/modal.calendar.html',
        },
        {
          title: 'portals.theme.title',
          content: 'js/XG/modules/portals/views/modals/modal.theme.html',
        },
        {
          title: 'portals.elastic.title',
          content: 'js/XG/modules/portals/views/modals/modal.elastic.html',
        },
        {
          title: 'portals.geocodage.title',
          content: 'js/XG/modules/portals/views/modals/modal.kisgeocodage.html',
        },
        {
          title: 'portals.apikey.title',
          content: 'js/XG/modules/portals/views/modals/modal.apikey.html',
          /* ,
                 {
                 "title": "model.featuretypes.attributes.title",
                 "content": "js/XG/modules/model/views/modals/modal.featuretypes_attributes.html"
                 }*/
        },
        {
          title: 'portals.traduction.title',
          content: 'js/XG/modules/portals/views/modals/modal.traduction.html',
        },
        {
          title: 'portals.geonetwork.title',
          content: 'js/XG/modules/portals/views/modals/modal.geonetwork.html',
        },
        {
          title: 'portals.extra_authentication.title',
          content:
            'js/XG/modules/portals/views/modals/modal.extra_authentication.html',
        },
        {
          title: 'portals.process.title',
          content: 'js/XG/modules/portals/views/modals/modal.process.html',
        },
        {
          title: 'portals.portal_monitoring.title',
          content:
            'js/XG/modules/portals/views/modals/modal.portal_monitoring.html',
        },
        {
          title: 'portals.alert_message.title',
          content:
            'js/XG/modules/portals/views/modals/modal.alert_message.html',
        },
        {
          title: 'portals.settingPwd.title',
          content:
            'js/XG/modules/portals/views/modals/modal.settingPwd.html',
        },{
          title: 'portals.homepage.title',
          content:
              'js/XG/modules/portals/views/modals/modal.homepage.html',
        }
      ];
      if($rootScope.xgos.isroot){
        $scope.tabs.push({
          title: 'portals.visibilityMenu.title',
          content: 'js/XG/modules/portals/views/modals/modal.visibilityMenu.html',
        });
        $scope.tabs.push({
          title: 'portals.arcgis.title',
          content: 'js/XG/modules/portals/views/modals/modal.arcgis.html',
        });
      }

      $scope.prevActiveTab = $scope.tabs.activeTab = 0;
    };


    /**
     * on valide toutes les valeurs renseigné dans le settingComplextyPwd
     */
    $scope.settingPwdValidator = (type) => {
      const parameters = $scope.edit_resource.parameters;
      if (type === 'minimumNumberTotalCharacters') {
        if(angular.isDefined(parameters.settingPwd.minimumNumberTotalCharacters) &&
           parameters.settingPwd.minimumNumberTotalCharacters>50){
          parameters.settingPwd.minimumNumberTotalCharacters = 50;
          toastr.error($filter('translate')('portals.settingPwd.maximumNumberTotalCharacters'));
        }
      }
      if (type === 'minimumNumberDigits' || type === 'minimumNumberSpecialCharacters' || type=== 'minimumNumberUppercase'
           || type=== 'minimumNumberLowercase') {
        if(parameters.settingPwd.minimumNumberTotalCharacters ||
            parameters.settingPwd.minimumNumberTotalCharacters==0){
          if(type === 'minimumNumberDigits' &&  parameters.settingPwd.minimumNumberTotalCharacters<
                parameters.settingPwd.minimumNumberDigits){
            parameters.settingPwd.minimumNumberDigits = parameters.settingPwd.minimumNumberTotalCharacters;
            require('toastr').error($filter('translate')('portals.settingPwd.minimumNumberDigitsGretterCharacters'));
          } else if(type === 'minimumNumberSpecialCharacters' &&  parameters.settingPwd.minimumNumberTotalCharacters<
                parameters.settingPwd.minimumNumberSpecialCharacters){
            parameters.settingPwd.minimumNumberSpecialCharacters = parameters.settingPwd.minimumNumberTotalCharacters;
            require('toastr').error($filter('translate')('portals.settingPwd.minimumNumberSpecialCharactersGretterCharacters'));
          } else if(type === 'minimumNumberUppercase' &&  parameters.settingPwd.minimumNumberTotalCharacters<
                parameters.settingPwd.minimumNumberUppercase){
            parameters.settingPwd.minimumNumberUppercase = parameters.settingPwd.minimumNumberTotalCharacters;
            require('toastr').error($filter('translate')('portals.settingPwd.minimumNumberUppercaseGretterCharacters'));
          } else if(type === 'minimumNumberLowercase' &&  parameters.settingPwd.minimumNumberTotalCharacters<
                parameters.settingPwd.minimumNumberLowercase){
            parameters.settingPwd.minimumNumberLowercase = parameters.settingPwd.minimumNumberTotalCharacters;
            require('toastr').error($filter('translate')('portals.settingPwd.minimumNumberLowercaseGretterCharacters'));
          }
        } else {
          parameters.settingPwd.minimumNumberDigits = 0;
          parameters.settingPwd.minimumNumberSpecialCharacters= 0;
          parameters.settingPwd.minimumNumberUppercase= 0;
          parameters.settingPwd.minimumNumberLowercase= 0;
          require('toastr').error($filter('translate')('portals.settingPwd.minimumNumberTotalCharactersIsEmpty'));
        }
      }
    };

    $scope.settingPwdDefaultValues = () => {
      if(!$scope.edit_resource.parameters.settingPwd){
        $scope.edit_resource.parameters.settingPwd = {
          minimumNumberTotalCharacters : 10,
          minimumNumberDigits: 1,
          minimumNumberSpecialCharacters: 1,
          minimumNumberUppercase: 1,
          minimumNumberLowercase: 1,
          renewalPwd: 12,
          forceRenewalNextLogin: false
        };
      }
      $scope.forceRenewalNextLogin();
    };

    $scope.changeDatePickerPwd = () => {
      $scope.edit_resource.parameters.settingPwd.forceRenewalNextLoginDate = $filter('date')($scope.edit_resource.parameters.settingPwd.datePickerPwd, 'dd/MM/yyyy');
      $scope.edit_resource.parameters.settingPwd.forceRenewalNextLogin = true;
      $scope.forceRenewalNextLogin();
    }

    $scope.forceRenewalNextLogin = () => {
      if($scope.edit_resource.parameters.settingPwd && $scope.edit_resource.parameters.settingPwd.forceRenewalNextLogin){
        if(!$scope.edit_resource.parameters.settingPwd.forceRenewalNextLoginDate){
          require('toastr').error(
            $filter('translate')('portals.settingPwd.noDateRenewalPwd')
          );
          $scope.edit_resource.parameters.settingPwd.forceRenewalNextLogin = false;
        }else {
          let date = $scope.edit_resource.parameters.settingPwd.forceRenewalNextLoginDate.split('/');
          $scope.edit_resource.parameters.settingPwd.datePickerPwd = new Date(date[2],date[1] - 1,date[0]);
          $scope.forceRenewalNextLoginMsg = $filter('translate')('portals.settingPwd.forceRenewalNextLoginMsg').replace(
            '$1',$scope.edit_resource.parameters.settingPwd.forceRenewalNextLoginDate)
        }
      }else{
        $scope.forceRenewalNextLoginMsg = '';
      }
    }

    $scope.settingPwdRestaurer = () => {
      $scope.edit_resource.parameters.settingPwd = {
        minimumNumberTotalCharacters : 10,
        minimumNumberDigits: 1,
        minimumNumberSpecialCharacters: 1,
        minimumNumberUppercase: 1,
        minimumNumberLowercase: 1,
        renewalPwd: 12,
        forceRenewalNextLogin: false,
        datePickerPwd: null
      }
    }
    $scope.displayIGNPopup = () => {
      ngDialog.open({
        template:
          'js/XG/modules/portals/views/modals/modal.portals.ign.html',
        className: 'ngdialog ngdialog-overlay ngdialog-theme-plain width800',
        closeByDocument: false,
      });
    }
    /**
     * displayOmegaExemple
     * Displays an exemple of an omega configuration file
     */
    $scope.displayOmegaExemple = function() {
      ngDialog.open({
        template:
          'js/XG/modules/portals/views/modals/modal.portals.omega_example.html',
        className: 'ngdialog ngdialog-overlay ngdialog-theme-plain width800',
        closeByDocument: false,
      });
    };
    /**
     * Omega Json File Configuration
     */
    $scope.isJsonValid = true;
    $scope.jsonEdition = {
      name: 'omegaJsonFile',
      data: {},
      options: {
        mode: 'code'
      }
    };

    /**
     * openFeatureTypeConfigJson
     */
    $scope.openConfigJson = () => {
      OmegaFactory.getDataFromFileJson().then((res) => {
        $scope.jsonEdition.data = res.data;
        ngDialog.open({
          template:
            'js/XG/modules/model/views/modals/modal.edition_json.html',
          className: 'ngdialog-theme-plain large',
          closeByDocument: false,
          scope: $scope,
        });
      })
    };
    /**
     * openPcWinConfigJson
     * Affiche le contenu du fichier pcwin (s'il existe) dans l'interface d'administration.
     */
    $scope.openPcWinConfigJson = () => {
      PcwinFactory.getDataFromPcwinJson().then((res) => {
        $scope.jsonEdition.name = "PCWIN";
        $scope.jsonEdition.data = res.data;
        ngDialog.open({
          template:
            'js/XG/modules/model/views/modals/modal.edition_json.html',
          className: 'ngdialog-theme-plain large',
          closeByDocument: false,
          scope: $scope,
        });
      });
    };
    /**
     * Change the json mode
     */
    $scope.jsonEditionChangeMode = () => {
      $scope.jsonEdition.options.mode
        = ($scope.jsonEdition.options.mode === 'code') ? 'tree' : 'code';
    };
    /**
     * Edit in the json file
     */
    $scope.editFeatureTypeJSON = () => {
      if ($scope.jsonEdition.data != {}) {
        gaDomUtils.showGlobalLoader();
        // Omega Case
        if($scope.jsonEdition.name == "omegaJsonFile"){
          OmegaFactory.updateJsonFile($scope.jsonEdition.data).then((res) => {
            if (res.data) {
              require('toastr').success(
                $filter('translate')('model.featuretypes.editionjson_ok')
              );
              gaDomUtils.hideGlobalLoader();
              ngDialog.close();
            }
          }, (error) => {
            require('toastr').error(
              $filter('translate')('model.featuretypes.editionjson_nok')
            );
            gaDomUtils.hideGlobalLoader();
          });
        }
        //PCWIN Case
        if($scope.jsonEdition.name == "PCWIN") {
          PcwinFactory.updatePcwinJsonFile($scope.jsonEdition.data).then((res) => {
            if (res.data) {
              require('toastr').success(
                $filter('translate')('model.featuretypes.editionjson_ok')
              );
              gaDomUtils.hideGlobalLoader();
              ngDialog.close();
            }
          }, (error) => {
            require('toastr').error(
              $filter('translate')('model.featuretypes.editionjson_nok')
            );
            gaDomUtils.hideGlobalLoader();
          });
        }
      }
    };
    /**
     * displayOmegaExemple
     * Displays an exemple of an omega configuration file
     */
    $scope.displayVisibilityMenuExemple = function() {
      ngDialog.open({
        template: '<code style=" display: block; white-space: pre-wrap;  "><div>["users","groups","roles","restrictions","extra_authentication","datasources","features",<br/>'+
        '"basemap","units","style","networks","builder","documents","actions","calendar","tracker",<br/>'+
        '"printmodel","atlas","majicedigeo","portal_monitoring","checkUp","applications","parameters","phonesform",<br/>'+
        '"phonesformintervention","imei","licence","process","geopackage","docxprocess","configuration",<br/>'+
        '"logs"]</code></div>',
        plain: true,
        className: 'ngdialog-theme-plain width800',
        closeByDocument: false,
      });
    };

    /**
     * displayPCWin2Exemple
     * Displays an exemple of an pcwin2 configuration file
     */
    $scope.displayPCWin2Exemple = function() {
      ngDialog.open({
        template: 'js/XG/modules/portals/views/modals/modal.portals.pcwin2_example.html',
        className:
          'ngdialog ngdialog-overlay ngdialog-theme-plain width800',
        closeByDocument: false
      });
    };

    $scope.activeTabChanged = function() {
      if ($scope.tabs.activeTab == -1)
        $scope.tabs.activeTab = $scope.prevActiveTab;
      $scope.prevActiveTab = $scope.tabs.activeTab;
    };

    $scope.dataStores = [];

    /**
     * Récupèration de la configuration du widget et la charge dans le scope courant.
     * @param portalId
     */
    $scope.getDataStores = function(portalId) {
      DataStoreFactory.get(portalId).then(
        function(res) {
          if (res.data !== '' && res.status == 200) {
            $scope.dataStores = res.data;
          }
        },
        function(reason) {
          require('toastr').error(reason);
        }
      );
    };

    /* When a portal is edited */
    $scope.$on('data_modal', function(event, args) {
      // retrieve the datastore for the currently edited portal, and not for
      if (args.action == 'edit') {
        if (!args.isNew) {
          $scope.getDataStores($scope.edit_resource.uid);
        }
      }
    });

    $scope.editingPortal = function() {
      if (
        $scope.edit_resource == undefined ||
        $scope.edit_resource.sendMailCfg == null
      )
        $scope.cfg.sendMailServerType = '';
      else
        $scope.cfg.sendMailServerType =
          $scope.edit_resource.sendMailCfg.sendServerType;

      if ($scope.edit_resource && $scope.edit_resource.parameters) {
        if (!$scope.edit_resource.parameters.hasOwnProperty('arcgis') || !$scope.edit_resource.parameters.arcgis.hasOwnProperty('esriIdField'))
          $scope.edit_resource.parameters.arcgis = {
            esriIdField: 'objectid'
          };
        $scope.theme = {
          selected: $scope.edit_resource.parameters.theme
        };
        // initialise le paramètre 'homepage' du portail s'il n'existe pas
        PortalsFactory.initHomepagePortalParameter($scope.edit_resource);
      }

      if ($scope.edit_resource && $scope.edit_resource.uid){
        const arcGISTabIndex = $scope.menuSetup.findIndex(tab => tab.label === 'portals.arcgis.title');
        if (arcGISTabIndex >= 0){
          DataStoreFactory.oneEsriDatasourceExists($scope.edit_resource.uid).then(
            res => {
              // res est true si le portail contient au moins 1 datasource ArcGIS
              $scope.menuSetup[arcGISTabIndex].disabled = !res;
            }
          );
        }

        // lecture du fichier "homepages.json" dans le dossier "CSS-HTML/homepage" du repo
        PortalsFactory.getHomepagesLight($scope.edit_resource.uid).then(
          res => {
            // renvoie tableau des noms et id des pages d'accueil du portail [{name,id},{...},...]
            $scope.edit_resource.homepagesLight = res.data;
            // ¡supprimer homepagesLight avant de sauvegarder edit_resource!
          },
          () => {
            require('toastr').error(
              $filter('translate')('portals.homepage.getHomepagesError'));
          }
        );
      }

      // Affiche le template de la rubrique "Base de données principale"
      $scope.curtemplate = $scope.menuSetup[0].template;

      // Active la rubrique "Base de données principale"
      for (const item of $scope.menuSetup) {
        if (item.selected) {
          item.selected = false;
        }
      }
      $scope.menuSetup[0].selected = true;
    };

    $scope.serverTypeChanged = function() {
      if ($scope.edit_resource == undefined) return;

      if ($scope.cfg.sendMailServerType == '')
        $scope.edit_resource.sendMailCfg = null;
      else {
        $scope.edit_resource.sendMailCfg = {};
        $scope.edit_resource.sendMailCfg.sendServerType =
          $scope.cfg.sendMailServerType;
      }
    };

    /**
     * Create or update the portal
     */
    $scope.editPortal = function() {

      // supprime la liste temporaire des pages d'accueil avant sauvegarde
      if (Array.isArray($scope.edit_resource.homepagesLight)) {
        delete $scope.edit_resource.homepagesLight;
      }

      if ($scope.isNewResource) {
        PortalsFactory.add($scope.edit_resource.name).then(function(res) {
          $scope.isNewResource = false;

          $scope.currentResources.push(res.data);
          PortalsFactory.sortPortalByNames($scope.currentResources);

          if (PortalsFactory.resources.portals.length == 1) {
            var ans = confirm($filter('translate')('portals.confirm_switch'));
            if (ans) {
              PortalsFactory.setPortal(PortalsFactory.resources.portals[0].uid);
              $window.location.reload();
            }
          }
          if ($scope.edit_resource.uid == $rootScope.xgos.portal.uid) {
            PortalsFactory.setPortal($scope.edit_resource.uid);
          }
        });
      } else {
        if ($scope.edit_resource.title==='') delete $scope.edit_resource.title;

        PortalsFactory.update($scope.edit_resource).then(function() {
          for (var i = 0; i < $scope.currentResources.length; i++) {
            if ($scope.currentResources[i].uid === $scope.edit_resource.uid) {
              $scope.currentResources[i] = angular.copy($scope.edit_resource);
              break;
            }
          }

          if ($scope.edit_resource.uid == $rootScope.xgos.portal.uid) {
            PortalsFactory.setPortal($scope.edit_resource.uid);
          }

          PortalsFactory.sortPortalByNames($scope.currentResources);
        });
      }
    };

    /**
     * Affiche les messages de succès et d'erreur provenant d'un objet de réponse.
     *
     * @param {Object} res - L'objet de réponse contenant infoList et errorList.
     * @return {void} Cette fonction ne renvoie aucune valeur.
     */
    const showMessagesFromResponse = (res) => {
      for (const info of res.data.infoList) {
        const mess = $filter('translate')('portals.'+info.message_kis);
        toastr.success(mess, undefined, toastrOptions);
      }
      for (const error of res.data.errorList) {
        toastr.error($filter('translate')('portals.'+error.message_kis),
          undefined, toastrOptions);
      }
    };


    /**
     * Portal removal
     */
    $scope.removePortal = function() {
      $scope.editListCfg.removeSpinner = true;
      PortalsFactory.remove($scope.edit_resource.uid).then((res) => {

        for (let i = 0; i < $scope.currentResources.length; i++) {
          if ($scope.currentResources[i].uid === $scope.edit_resource.uid) {
            $scope.currentResources.splice(i, 1);
            break;
          }
        }

        if ($rootScope.xgos.portal && $scope.edit_resource.uid == $rootScope.xgos.portal.uid) {
          if (PortalsFactory.resources.portals.length > 0) {
            PortalsFactory.setPortal(PortalsFactory.resources.portals[0].uid);
            $window.location.reload();
          } else {
            PortalsFactory.setNoPortal();
          }
        }
        showMessagesFromResponse(res);
      }).finally(() => {
        $scope.editListCfg.removeSpinner = false;
      });
    };

    /**
     * Portals loading
     * loader from the portal switcher
     */
    $scope.$watch(
      function() {
        return $rootScope.portals;
      },
      function() {
        if (typeof $rootScope.portals !== 'undefined') {
          $scope.currentResources = $rootScope.portals.filter(function(x) {
            // plus possible de lister les portails des autres en superAdmin, vu avec frt @26.06.18
            if (
              $rootScope.xgos.isroot ||
              ($rootScope.xgos.isadmin && x.uid === $rootScope.xgos.portal.uid)
            )
              return x;
          });
        }
      }
    );

    $scope.reloadAll = function() {
      swal(
        {
          title: 'Attention',
          text:
            $filter('translate')('portals.reloadAll') +
            '. ' +
            $filter('translate')('portals.reloadSur'),
          type: 'warning',
          showCancelButton: true,
          confirmButtonColor: '#DD6B55',
          confirmButtonText: $filter('translate')('common.yes'),
          cancelButtonText: $filter('translate')('common.no'),
          closeOnConfirm: true,
        },
        function(isConfirm) {
          if (isConfirm) {
            gaDomUtils.showGlobalLoader();
            PortalsFactory.reloadAll().then(
              function() {
                gaDomUtils.hideGlobalLoader();
                swal({
                  title: $filter('translate')('portals.reloadSuccess'),
                  type: 'success',
                  showCancelButton: false,
                  time: 600,
                });
              },
              function(res) {
                gaDomUtils.hideGlobalLoader();
                swal({
                  title: $filter('translate')('portals.reloadEchec'),
                  text: res.data,
                  type: 'error',
                  showCancelButton: false,
                  confirmButtonColor: '#DD6B55',
                  confirmButtonText: $filter('translate')('common.yes'),
                  closeOnConfirm: true,
                });
              }
            );
          }
        }
      );
    };

    $scope.reloadPortal = function() {
      swal(
        {
          title: 'Attention',
          text:
            $filter('translate')('portals.reloadPortal') +
            ' ' +
            $scope.edit_resource.name +
            '. ' +
            $filter('translate')('portals.reloadSur'),
          type: 'warning',
          showCancelButton: true,
          confirmButtonColor: '#DD6B55',
          confirmButtonText: $filter('translate')('common.yes'),
          cancelButtonText: $filter('translate')('common.no'),
          closeOnConfirm: true,
        },
        function(isConfirm) {
          if (isConfirm) {
            gaDomUtils.showGlobalLoader();
            PortalsFactory.reloadPortal($scope.edit_resource.uid).then(
              function() {
                gaDomUtils.hideGlobalLoader();
                swal({
                  title: $filter('translate')('portals.reloadSuccess'),
                  type: 'success',
                  showCancelButton: false,
                  time: 600,
                });
              },
              function(res) {
                gaDomUtils.hideGlobalLoader();
                swal({
                  title: $filter('translate')('portals.reloadEchec'),
                  text: res.data,
                  type: 'error',
                  showCancelButton: false,
                  confirmButtonColor: '#DD6B55',
                  confirmButtonText: $filter('translate')('common.yes'),
                  closeOnConfirm: true,
                });
              }
            );
          }
        }
      );
    };

    $rootScope.portals = PortalsFactory.resources.portals;

    /**
     * EditList Directive configuration
    */
    $scope.editListCfg = {
      dataModule: 'portals',
      resource_type: 'portals',
      cols: ['uid', 'name'],
      removeSpinner: false,
      removeFunction: $scope.removePortal,
      defautValues: [
        { k: 'title', v: 'KIS - Knowledge Information System' },
        { k: 'parameters', v: {} },
      ],
      width: 'width1000',
    };
    if ($rootScope.xgos.isadmin && !$rootScope.xgos.isroot) {
      //if($rootScope.xgos.isadmin && !$rootScope.xgos.isroot && !$rootScope.xgos.isSuperAdmin){
      $scope.editListCfg.addResourceButton = false;
      $scope.editListCfg.deleteResourceButton = false;
    }
    if ($rootScope.xgos.isroot) {
      $scope.editListCfg.extraGlobalActions = [
        {
          label: $filter('translate')('portals.reloadAll'),
          fn: $scope.reloadAll,
        },
        {
          label: $filter('translate')('portals.reloadPortal'),
          fn: $scope.reloadPortal,
          disablefn: function() {
            return !($scope.edit_resource && $scope.edit_resource.uid);
          },
        },
      ];
    }

    $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
      );
    };

    $scope.tmpCalendar = { activated: 0 };
    $scope.activateCalendar = function() {
      gaDomUtils.showGlobalLoader();

      CalendarFactory.createeventtables(
        null,
        $scope.edit_resource.parameters.calendar.datastore_uid
      ).then(
        function() {
          $scope.edit_resource.parameters.calendar.active = true;
          require('toastr').success($filter('translate')('common.saved'));
          gaDomUtils.hideGlobalLoader();
          $timeout(function() {
            $window.location.reload();
          }, 500);
        },
        function(res) {
          require('toastr').error(res.data);
          gaDomUtils.hideGlobalLoader();
        }
      );

      /*setTimeout(function(){
             PortalsFactory.createeventtables($scope.tmpCalendarDataStore.name).then(function(){
             */
      /* console.log($scope.edit_resource);
             $scope.edit_resource.calendar = {
             active : true
             };
             console.log($scope.edit_resource);
             $scope.editPortal();*/
      /*
             gaDomUtils.hideGlobalLoader();
             }, function(){
             console.log('error');
             gaDomUtils.hideGlobalLoader();
             });
             }, 1000 );*/
    };

    $scope.validPortalCfg = function(type) {
      var p = $scope.edit_resource.parameters;
      if (!p) return;

      var valid = true;

      if (type == 'tracker' || !type) {
        valid =
          (!p.log_tracker_active && !p.datastore_log_tracker) ||
          (p.log_tracker_active && p.datastore_log_tracker);
      }
      if (valid && (type == 'history' || !type)) {
        if (p.history) {
          valid =
            (!p.history.active && !p.history.datastore_uid) ||
            (p.history.active && p.history.datastore_uid);
        }
      }

      return valid;
    };

    // init theme as default
    $scope.$on('data_modal', function() {
      if (angular.isUndefined($scope.edit_resource.theme)) {
        $scope.edit_resource.parameters.theme = 'default';
      }
      $scope.tabs.activeTab = 0;
    });

    $scope.defineTabs();
    $scope.$watch('tabs.activeTab', $scope.activeTabChanged);
    $scope.$watch('edit_resource', $scope.editingPortal);
    $scope.$watch('sendMailServerType', $scope.serverTypeChanged);

    // $scope.edit_resource.parameters.kisgeocodage = [];

    /* When a portal is edited */
    $scope.$on('data_modal', function() {
      if (
        !$scope.edit_resource.parameters.kisgeocodage ||
        $scope.edit_resource.parameters.kisgeocodage.length == 0
      ) {
        $scope.edit_resource.parameters.kisgeocodage = [
          /*           {
                        id: 'kis_geocoder_' + Date.now(),
                        label: '',
                        url: '',
                        detail: ''
                    }*/
        ];
      }

      if (!$scope.edit_resource.parameters.traductionLang)
        $scope.edit_resource.parameters.traductionLang =
          $scope.optslang[0].lang;

      $scope.edit_resource.parameters.choosenlanguages = angular.copy(
        $scope.optslang
      );

      $scope.calendarGeocoder = false;

      if (
        gaJsUtils.checkNestedProperty(
          'parameters.calendar.geocodage',
          $scope.edit_resource
        )
      ) {
        $scope.calendarGeocoder = true;
      }
    });

    /**
     * add new Geocodage
     */
    $scope.addNewGeoCodage = function() {
      $scope.edit_resource.parameters.kisgeocodage.push({
        id: 'kis_geocoder_' + Date.now(),
        label: '',
        url: '',
        detail: '',
      });
    };

    /**
     * remove Geocodage
     * @param index
     */
    $scope.removeGeoCodage = function(index) {
      var ans = confirm(
        $filter('translate')('portals.confirm_remove_geocodeur')
      );
      if (ans) {
        $scope.edit_resource.parameters.kisgeocodage.splice(index, 1);
      }
    };

    /**
     * check config kisGeocodage name
     * @returns {boolean}
     */
    var checkSameNameOfKisGeocodage = function() {
      $scope.kisgeocodagename = false;
      var res = false;
      var values = [];
      $scope.edit_resource.parameters.kisgeocodage.forEach(function(object) {
        values.push(object.label);
      });
      values.sort();
      for (var i = 0; i < values.length; i++) {
        if (values[i] == values[i + 1]) {
          res = true;
          $scope.kisgeocodagename = values[i];
        }
      }
      return res;
    };

    $scope.validGeocodageName = false;
    $scope.$watch(
      'edit_resource.parameters.kisgeocodage',
      function(v) {
        if (v) {
          $scope.validGeocodageName = false;
          if (checkSameNameOfKisGeocodage() == true) {
            $scope.validGeocodageName = true;
          }
        }
      },
      1
    );

    $scope.changeCalendarGeocoder = function() {
      $scope.calendarGeocoder = !$scope.calendarGeocoder;
      if (!$scope.calendarGeocoder) {
        $scope.edit_resource.parameters.calendar.geocodage = false;
      }
    };

    var role = $rootScope.xgos.user.roles.map(function(x) {
      return x.name;
    });
    $scope.showDeleteElasticBtn = false;
    if (role.indexOf('rootUser') !== -1) $scope.showDeleteElasticBtn = true;

    $scope.removeIndexElastic = function() {
      var ans = confirm($filter('translate')('common.confirm_action'));
      if (ans) {
        var portalid = $scope.edit_resource.uid;
        if (portalid)
          ElasticFactory.deleteIndex(portalid).then(
            function() {
              require('toastr').success(
                $filter('translate')('portals.elastic.ok')
              );
            },
            function() {
              require('toastr').error(
                $filter('translate')('portals.elastic.nok')
              );
            }
          );
      }
    };

    $scope.optslang = [
      {
        text: "<i class='flag flag-fr'></i> Français",
        lang: 'fr',
      },
      {
        text: "<i class='flag flag-gb'></i> English",
        lang: 'en',
      },
      {
        text: "<i class='flag flag-de'></i> Deutsch",
        lang: 'de',
      },

      {
        text: "<i class='flag flag-pl'></i> Polski",
        lang: 'pl',
      },
      {
        text: "<i class='flag flag-es'></i> Español",
        lang: 'es',
      },
      {
        text: "<i class='flag flag-mx'></i> Español",
        lang: 'mx',
      },
      {
        text: "<i class='flag flag-kh'></i> ភាសាខ្មែរ",
        lang: 'km',
      },
      {
        text: "<i class='flag flag-cn'></i> 中文",
        lang: 'zh-CN',
      },
      {
        text: ' اللغة العربية‎',
        lang: 'ar',
      },
    ];

    $scope.changedLang = function(val) {
      if (val && $scope.edit_resource.parameters.choosenlanguages) {
        $scope.edit_resource.parameters.choosenlanguages.map(function(x) {
          if (x.lang === val && x.selected) x.selected = false;
        });
      }
    };

    $scope.applyTraduction = function() {
      if (
        $scope.edit_resource.parameters &&
        $scope.edit_resource.parameters.choosenlanguages
      )
        var langs = $scope.edit_resource.parameters.choosenlanguages
          .map(function(x) {
            if (
              x.selected &&
              x.lang !== $scope.edit_resource.parameters.traductionLang
            )
              return x.lang;
          })
          .filter(function(x) {
            if (x) return x;
          });
      if (langs) {
        PortalsFactory.applyTraduction(
          $scope.edit_resource.uid,
          langs.join(','),
          $scope.edit_resource.parameters.traductionLang
        ).then(
          function() {
            require('toastr').success(
              $filter('translate')('portals.traduction.ok')
            );
          },
          function() {
            require('toastr').error(
              $filter('translate')('portals.traduction.nok')
            );
          }
        );
      } else {
        require('toastr').error(
          $filter('translate')('portals.traduction.nolanguagetocopy')
        );
      }
    };

    $scope.selectAll = function() {
      $scope.edit_resource.parameters.choosenlanguages.map(function(x) {
        if (x.lang !== $scope.edit_resource.parameters.traductionLang)
          x.selected = true;
      });
    };

    $scope.removeAll = function() {
      $scope.edit_resource.parameters.choosenlanguages.map(function(x) {
        x.selected = false;
      });
    };

    $scope.search = function(item) {
      console.log($scope.searchText);
      if ($scope.searchText == undefined) {
        return true;
      } else {
        console.log(item);
        console.log($scope.searchText);
        if (
          item.name.toLowerCase().indexOf($scope.searchText.toLowerCase()) !=
            -1 ||
          item.applications.applications.type
            .toLowerCase()
            .indexOf($scope.searchText.toLowerCase()) != -1
        ) {
          return true;
        }
      }
      return false;
    };

    /**
     * Par défaut la couleur de la couche d'accroche (Rose logo KIS)
     */
    $scope.colorInit = () => {
      if(!$scope.edit_resource.parameters.snapColor){
        $scope.edit_resource.parameters.snapColor='#f31f72';
      }
    }
    
    /**
     * Supprime le thème des utilisateurs ayant un thème défini
     * quand on décoche la case de l'onglet "Thèmes":
     * "Permettre aux utilisateurs d'assombrir le thème défault"
     */
    $scope.removeAllUsersTheme = () => {
      // est false au décochage de la case 'portals.theme.authorize' dans modal.theme.html
      ThemesFactory.removeAllUsersTheme($scope.edit_resource.uid,
        $scope.edit_resource.parameters.allowUserTheme);
    };
    /**
     * Au changement du select de l'onglet "Thèmes" de la popup d'édition d'un portail,
     * on met à jour le paramètre du portail à partir de l'objet $scope.theme
     */
    $scope.onChangeTheme = () => {
      if ($scope.theme && $scope.theme.selected !== undefined){
        $scope.edit_resource.parameters.theme = $scope.theme.selected;
      }
    };

    /**
     * Ajoute le rôle 'kis_homepage' dans le repo et dans le tableau resources.rolesLight
     * quand on coche la case de située dans l'onglet "Page d'accueil" du portail.<br>
     * Quand on décoche la case, on supprime le rôle 'kis_homepage'
     * dans le repo et dans le tableau resources.rolesLight
     */
    $scope.activeHomepageChange = () => {
      if (gaJsUtils.notNullAndDefined($scope.edit_resource, 'parameters.homepage.active')
          && $scope.edit_resource.uid) {
        const homepageRoleName = 'kis_homepage';
        const homepageActuRoleName = 'kis_homepage_actu';

        if ($scope.edit_resource.parameters.homepage.active){

          // pour permettre l'activation de la page d'accueil perso,
          // on vérifie si le portail courant possède une source de données active
          if (checkMainDbOnHomepageActivation()) {
            // la case est cochée
            $scope.edit_resource.parameters.homepage.activename = 'v2';

            // ajoute le rôle kis_homepage dans le repo et dans le tableau resources.rolesLight
            const homepageRole = {
              name: homepageRoleName,
              rightFeatures:[],
              authorizations:[],
              description: null
            };
            RolesFactory.addIfNotExists(homepageRole);

            // ajoute le rôle ~_actu dans le repo et dans le tableau resources.rolesLight
            const homepageActuRole = Object.assign({}, homepageRole);
            homepageActuRole.name = homepageActuRoleName;
            RolesFactory.addIfNotExists(homepageActuRole);

          } else {
            // si aucune source de données n'est activée,
            // on affiche un swal et on laisse la case décochée
            $scope.edit_resource.parameters.homepage.active = false;
          }
        }
        else if ($scope.edit_resource.parameters.homepage.hasOwnProperty('activename')) {

          // la case a été décochée
          $scope.edit_resource.parameters.homepage.activename = null;

          // supprime le rôle kis_homepage dans le repo et dans le tableau resources.rolesLight
          RolesFactory.removeByUid(homepageRoleName);

          // supprime le rôle ~_actu dans le repo et dans le tableau resources.rolesLight
          RolesFactory.removeByUid(homepageActuRoleName);
        }
      }
    };

    /**
     * Ouvre la confirmation de suppression d'une page d'accueil.<br>
     * Créé une variable temporaire <code>selectedHomepage</code>
     * dans le portail courant <code>edit_resource</code>
     * @param index rang de la page d'accueil dans le tableau edit_resource.homepagesLight
     */
    $scope.openConfirmDeleteHomepage = (index) => {
      if ($scope.edit_resource && Array.isArray($scope.edit_resource.homepagesLight)
          && Number.isInteger($scope.edit_resource.homepagesLight[index].id)) {
        $scope.edit_resource.selectedHomepage = {
          name: $scope.edit_resource.homepagesLight[index].name,
          id: $scope.edit_resource.homepagesLight[index].id,
          index: index
        };
        $scope.deleteModalTitle = $filter('translate')('portals.homepage.confirm');
        ngDialog.open({
          template:
              'js/XG/modules/portals/views/modals/modal.homepage.delete.html',
          className: 'ngdialog-theme-plain width300 miniclose',
          closeByDocument: false,
          scope: $scope,
          preCloseCallback: () => {
            $scope.deleteModalTitle = null;
            if ($scope.edit_resource.selectedHomepage
                && !$scope.edit_resource.selectedHomepage.isDeleting) {
              delete $scope.edit_resource.selectedHomepage;
            }
          }
        });
      }
    };

    /**
     * Supprime la page d'accueil du portail
     * Renvoie true si la suppression dans le fichier 'homepages.json' du repo est réussie.
     */
    $scope.deleteHomepage = () => {
      if ($scope.edit_resource && $scope.edit_resource.selectedHomepage) {
        $scope.edit_resource.selectedHomepage.isDeleting = true;
        PortalsFactory.deleteHomepageById(
          $scope.edit_resource.uid,
          $scope.edit_resource.selectedHomepage.id
        ).then(
          res => {
            if (res.data) {
              // homepagesLight: créé à l'édition (@see editingPortal)
              // et supprimé avant sauvegarde du portail (@see editPortal)
              if (Array.isArray($scope.edit_resource.homepagesLight) && Number.isInteger(
                $scope.edit_resource.selectedHomepage.index)
                    && $scope.edit_resource.selectedHomepage.index > -1) {
                $scope.edit_resource.homepagesLight.splice(
                  $scope.edit_resource.selectedHomepage.index, 1);
              }
            } else {
              require('toastr').error($filter('translate')('portals.homepage.deleteError'));
            }
          },
          err => {
            console.log(err && err.data && err.data.message ? err.data.message : '');
            require('toastr').error($filter('translate')('portals.homepage.deleteError'));
          }
        ).finally(
          () => {
            // supprime la page d'accueil sélectionnée du portail courant
            delete $scope.edit_resource.selectedHomepage;
          }
        );
      } else {
        require('toastr').error($filter('translate')('portals.homepage.noPortal') + ' / \n' +
          $filter('translate')('portals.homepage.noHomepageSelected')
        );
      }
    };

    /**
     * Au cochage de l'activation de la page d'accueil,
     * vérifie si le portail courant possède une source de données active
     * afin de pouvoir récupérer les données de la table du fil d'actualités
     * @return {boolean} true si le portail courant détient une source de données active
     */
    const checkMainDbOnHomepageActivation = () => {
      if (gaJsUtils.notNullAndDefined($scope.edit_resource, 'parameters.mainDB')
          && (typeof $scope.edit_resource.parameters.mainDB === 'string'
          && $scope.edit_resource.parameters.mainDB.length > 0)) {
        return true;
      } else {
        swal({
          title: $filter('translate')('portals.homepage.v2.noMainDbTitle'),
          text: $filter('translate')('portals.homepage.v2.noMainDbText'),
          type: 'error',
          confirmButtonColor: '#DD6B55',
          closeOnConfirm: true,
        });
        return false;
      }
    };

    // arbre des rubriques de l'édition d'un portail: abn_tree.tree-data
    $scope.menuSetup = [
      {
        label: 'portals.mainDB.title',
        template: 'js/XG/modules/portals/views/modals/modal.mainDB.html'
      },
      {
        label: 'portals.regional.title',
        template: 'js/XG/modules/portals/views/modals/modal.regional.html',
      },
      {
        label: 'portals.sendmail.title',
        template: 'js/XG/modules/portals/views/modals/modal.sendmail.html',
      },
      {
        label: 'portals.tracker.title',
        template: 'js/XG/modules/portals/views/modals/modal.tracker.html',
      },
      {
        label: 'portals.history.title',
        template: 'js/XG/modules/portals/views/modals/modal.history.html',
      },
      {
        label: 'portals.calendar.title',
        template: 'js/XG/modules/portals/views/modals/modal.calendar.html',
      },
      {
        label: 'portals.theme.title',
        template: 'js/XG/modules/portals/views/modals/modal.theme.html',
      },
      {
        label: 'portals.elastic.title',
        template: 'js/XG/modules/portals/views/modals/modal.elastic.html',
      },
      {
        label: 'portals.geocodage.title',
        template: 'js/XG/modules/portals/views/modals/modal.kisgeocodage.html',
      },
      {
        label: 'portals.apikey.title',
        template: 'js/XG/modules/portals/views/modals/modal.apikey.html',
      },
      {
        label: 'portals.traduction.title',
        template: 'js/XG/modules/portals/views/modals/modal.traduction.html',
      },
      {
        label: 'portals.geonetwork.title',
        template: 'js/XG/modules/portals/views/modals/modal.geonetwork.html',
      },
      {
        label: 'portals.extra_authentication.title',
        template: 'js/XG/modules/portals/views/modals/modal.extra_authentication.html',
      },
      {
        label: 'portals.process.title',
        template: 'js/XG/modules/portals/views/modals/modal.process.html',
      },
      {
        label: 'portals.portal_monitoring.title',
        template: 'js/XG/modules/portals/views/modals/modal.portal_monitoring.html',
      },
      {
        label: 'portals.alert_message.title',
        template: 'js/XG/modules/portals/views/modals/modal.elastic.html',
      },
      {
        label: 'portals.settingPwd.title',
        template: 'js/XG/modules/portals/views/modals/modal.settingPwd.html',
      },
      {
        label: 'portals.homepage.title',
        template: 'js/XG/modules/portals/views/modals/modal.homepage.html',
      }
    ];

    if($rootScope.xgos.isroot){
      $scope.menuSetup.push({
        label: 'portals.visibilityMenu.title',
        template: 'js/XG/modules/portals/views/modals/modal.visibilityMenu.html',
      });
      $scope.menuSetup.push({
        label: 'portals.arcgis.title',
        template: 'js/XG/modules/portals/views/modals/modal.arcgis.html',
      });
    }

    /**
     * Action au clic sur une rubrique de l'éditeur de portail:<ul><li>
     * active la branche cliquée</li><li>
     * Affiche le template de la branche cliquée</li></ul>
     * @param {object} branch objet de menuSetup
     */
    $scope.tree_handler = function(branch) {
      for (const branch of $scope.menuSetup) {
        delete branch.selected;
      }
      branch.selected = true;
      $scope.curtemplate = branch.template;

      if (branch.label === 'portals.regional.title' && !$scope.edit_resource.parameters.regional) {
        $scope.edit_resource.parameters.regional =  {};
      }
    };

    RegionalFactory.getTextEncodings().then(
      res =>  {
        $scope.textEncodings = res;
      }
    );
    RegionalFactory.getCsvColumnSeparators().then(
      res => {
        $scope.csvColumnSeparators = res;
      }
    );
  };

  PortalsCtrl.$inject = [
    '$scope',
    '$rootScope',
    '$window',
    '$filter',
    'PortalsFactory',
    'OmegaFactory',
    'DataStoreFactory',
    'gaDomUtils',
    'CalendarFactory',
    '$timeout',
    'gaJsUtils',
    'ElasticFactory',
    'ngDialog',
    'ThemesFactory',
    'RolesFactory',
    'RegionalFactory',
    'PcwinFactory'
  ];
  return PortalsCtrl;
});
