/**
 *
 */
'use strict';
define(function() {
  /**
   * ApplicationCtrl
   * @param $scope
   * @param $window
   * @param $location
   * @param ApplicationFactory
   * @param RolesFactory
   * @constructor
   */
  var ApplicationCtrl = function(
    $scope,
    $window,
    $location,
    ApplicationFactory,
    RolesFactory,
    ngDialog,
    $timeout,
    $filter,
    FunctionFactory,
    $http,
    licenceFactory,
    $rootScope,
    $interval,
    DataStoreFactory,
    CarteAppFactory,
    AlertHpoFactory,
    gaDomUtils,
    ConfigFactory,
    SridFactory,
    PortalsFactory
  ) {
    /**
     * Create or update the application
     */
    $scope.editApplication = function() {
      if (angular.isUndefined($scope.edit_resource.type)) {
        require('toastr').error($filter('translate')('applications.applications.param_empty'));
        return;
      }
      $scope.edit_resource.roles = $scope.dLBRolesData.leftData;
      $scope.saveScalesToApp($scope.edit_resource.roles);
      if ($scope.isNewResource) {
        // cannot add more than one siroco
        if ($scope.edit_resource.type == 'Siroco') {
          var nbSiroco = 0;
          $scope.currentResources.forEach(function(a) {
            if (a.type == 'Siroco') nbSiroco++;
          });
          if (nbSiroco > 0) {
            alert(
              $filter('translate')(
                'applications.applications.siroco.portal_already_has_one'
              )
            );
            return;
          }
        }
        ApplicationFactory.add($scope.edit_resource).finally(()=>{
            $scope.getAndSaveSrid();
            $scope.currentResources = ApplicationFactory.resources.applications;
        });
      } else {
        ApplicationFactory.update($scope.edit_resource)
          .then( res => {
            require('toastr').success($filter('translate')('common.saved'));
          }
          ,error => {
            require('toastr').error(error.data.message);
          })
          .finally(()=>{
            $scope.getAndSaveSrid();
            $scope.currentResources = ApplicationFactory.resources.applications;
        });
      }
    };

    $scope.cancreate = true;
    var checkLicenceApp = function() {
      licenceFactory.canCreateApp().then(
        function(res) {
          if (res && angular.isDefined(res.data))
            $scope.cancreate = JSON.parse(res.data);
        },
        function(res) {
          $scope.cancreate = true;
        }
      );
    };
    checkLicenceApp();

    var stop;
    $timeout(function() {
      if (
        $rootScope.xgos.licence &&
        $rootScope.xgos.licence.full &&
        $rootScope.xgos.licence.full.type === 'kis_licence' &&
        angular.isDefined($rootScope.xgos.licence.full.nbapplications) &&
        $rootScope.xgos.licence.full.nbapplications !== '*' &&
        $rootScope.xgos.licence.full.nbapplications !== null &&
        $rootScope.xgos.licence.full.nbapplications >= 0
      )
        stop = $interval(function() {
          checkLicenceApp();
        }, 10000000);
    }, 5000);

    /**
     * copy the application
     * @param name
     */
    $scope.copyApp = function(name) {
      var ans = confirm(
        $filter('translate')('applications.applications.copy_confirm')
      );
      if (ans) {
        ApplicationFactory.copy($scope.edit_resource, name).finally(()=>{
          $scope.currentResources = ApplicationFactory.resources.applications;
        });
      }
    };

    /**
     * Application removal
     */
    $scope.removeApplication = function() {
      ApplicationFactory.remove($scope.edit_resource.name).finally(()=>{
        $scope.currentResources = ApplicationFactory.resources.applications;
      });
    };

    // get Roles
    if (!RolesFactory.resources.roles.length) RolesFactory.get();
    ApplicationFactory.get().then(function() {
      $timeout(function() {
        $scope.currentResources = ApplicationFactory.resources.applications;
      });
    });

    /**
     * Open Config Browser
     * @param $index
     */
    $scope.openConfigBrowser = function() {
      //scope.browsefor = $index;
      ngDialog.open({
        template: 'js/XG/widgets/utilities/form/views/modal/builderOpen.html',
        className: 'ngdialog-theme-plain width1000 nopadding miniclose',
        closeByDocument: false,
        scope: $scope,
      });
    };
    /*        $scope.applicationTypes = [
            {'name':'MapApp','value' : 'MapApp'},
            {'name':'FormApp','value' : 'FormApp'},
        ];*/

    $scope.applicationTypes = [
      {
        key: 'MapApp',
        label: 'applications.types.map',
      },
    ];
    if ($rootScope.xgos.isroot)
      $scope.applicationTypes.push({
        key: 'MapAppV2',
        label: 'applications.types.mapv2',
      });

    $scope.applicationTypes = $scope.applicationTypes.concat([
      {
        key: 'FormApp',
        label: 'applications.types.form',
      },
      {
        key: 'Siroco',
        label: 'applications.types.siroco',
      },
      {
        key: 'Indigau',
        label: 'applications.types.indigau',
      },
      {
        key: 'CustomHtml',
        label: 'applications.types.customhtml',
      },
      {
        key: 'AncApp',
        label: 'applications.types.anc',
      },
      {
        key: 'BacApp',
        label: 'applications.types.bac',
      },
      {
        key: 'HpoApp',
        label: 'applications.types.hpo',
      },
    ]);
    $scope.srids = SridFactory.sridsList;

    /**
     * displayApp
     * @returns {string}
     */
    $scope.displayApp = function(app) {
      return (
        '<div class=\'apppicker_data ' +
        app.key +
        '\'>' +
        '<div class=\'apppicker_label\'> ' +
        $filter('translate')(app.label + '.title') +
        ' </div>' +
        '<div class=\'apppicker_desc\'> ' +
        $filter('translate')(app.label + '.description') +
        ' </div>' +
        '</div>'
      );
    };
    $scope.selectedsrid = {};
    $scope.getAndSaveSrid = function() {
      $scope.selectedsrid.name = $scope.edit_resource.outsrid;
      SridFactory.getbycode($scope.selectedsrid.name).then(function(res) {
        $scope.selectedsrid.description = res.data;
        if (!$rootScope.xgos.mouseposition) $rootScope.xgos.mouseposition = {};
        $scope.currentsrid = $scope.selectedsrid;
        $rootScope.xgos.mouseposition.srid = $scope.currentsrid;
        ConfigFactory.add(
          $scope.currentsrid,
          'main',
          'coordinate',
          $scope.edit_resource.name
        ).then(
          function(res) {
            ConfigFactory.reprojectExtend(
              $scope.currentsrid.name,
              'main',
              'map',
              $scope.edit_resource.name
            ).then(function(res) {});
            require('toastr').success($filter('translate')('applications.applications.srid_saved'));
          },
          function(reason) {
            require('toastr').error(reason);
          }
        );
      });
    };

    /* ]{
            "MapApp"            : "MapApp",
            "FormApp"           : "FormApp",
            "Siroco"            : "Siroco",
            "Indigau"           : "Indigau",
            "CustomHtml"        : "CustomHtml",
            "AncApp"            : "AncApp",
        };*/

    /**
     * Open the app in a new tab
     */
    $scope.goToApplication = function() {
      /*$location.path(
                $scope.edit_resource.type.replace('App','').toLowerCase()
            ).search({
                portal : PortalsFactory.getPortalId(),
                app : $scope.edit_resource.name
            });*/

      var appTpl = $scope.edit_resource.type.replace('App', '').toLowerCase();

      $window.open(
        '#/' +
          appTpl +
          '?portal=' +
          PortalsFactory.getPortalId() +
          '&app=' +
          $scope.edit_resource.name
      );
    };

    /**
     * Open the app in a new tab in configure mode
     */
    $scope.goToCfg = function() {
      //console.log($scope.edit_resource);
      var appTpl = $scope.edit_resource.type.replace('App', '').toLowerCase();
      if (
        $scope.edit_resource.params.operis &&
        $scope.edit_resource.params.operis == true
      ) {
        $window.open(
          '#/' +
            appTpl +
            '?portal=' +
            PortalsFactory.getPortalId() +
            '&app=' +
            $scope.edit_resource.name +
            '&mode=config' +
            '&operis=1'
        );
      } else {
        $window.open(
          '#/' +
            appTpl +
            '?portal=' +
            PortalsFactory.getPortalId() +
            '&app=' +
            $scope.edit_resource.name +
            '&mode=config'
        );
      }
    };

    /**
     * Open the app in a new tab
     */
    $scope.goToApplicationMap = function() {
      /*$location.path(
                $scope.edit_resource.type.replace('App','').toLowerCase()
            ).search({
                portal : PortalsFactory.getPortalId(),
                app : $scope.edit_resource.name
            });*/

      var appTpl = $scope.edit_resource.type
        .replace('App', '')
        .replace('V2', '')
        .toLowerCase();

      $window.open(
        '#/' +
          appTpl +
          '?portal=' +
          PortalsFactory.getPortalId() +
          '&app=' +
          $scope.edit_resource.name
      );
    };

    /**
     * Open the app in a new tab in configure mode
     */
    $scope.goToCfgMap = function() {
      console.log($scope.edit_resource);
      var appTpl = $scope.edit_resource.type
        .replace('App', '')
        .replace('V2', '')
        .toLowerCase();
      if (
        $scope.edit_resource.params.operis &&
        $scope.edit_resource.params.operis == true
      ) {
        $window.open(
          '#/' +
            appTpl +
            '?portal=' +
            PortalsFactory.getPortalId() +
            '&app=' +
            $scope.edit_resource.name +
            '&mode=config' +
            '&operis=1'
        );
      } else {
        $window.open(
          '#/' +
            appTpl +
            '?portal=' +
            PortalsFactory.getPortalId() +
            '&app=' +
            $scope.edit_resource.name +
            '&mode=config'
        );
      }
    };

    $scope.disableupgradetomapv2 = function() {
      if (
        !$scope.edit_resource ||
        !$scope.edit_resource.hasOwnProperty('name') ||
        $scope.selected_resource_index === -1 ||
        ($scope.edit_resource && $scope.edit_resource.type !== 'MapApp')
      )
        return true;
      else {
        return false;
      }
    };

    $scope.disableconfigmapv2 = function() {
      if (
        !$scope.edit_resource ||
        !$scope.edit_resource.hasOwnProperty('name') ||
        $scope.selected_resource_index === -1 ||
        ($scope.edit_resource && $scope.edit_resource.type !== 'MapAppV2')
      )
        return true;
      else {
        return false;
      }
    };

    $scope.isConfigDone = undefined;
    $scope.updateConfig = function() {
      gaDomUtils.showGlobalLoader();
      CarteAppFactory.updateConfig(
        $scope.CarteConfig,
        false,
        'mapv2',
        $scope.edit_resource.name
      ).then(
        function(res) {
          if (res && res.data) {
            $scope.CarteConfig = res.data;
            $scope.edit_resource.type = 'MapAppV2';
            ApplicationFactory.update($scope.edit_resource).then(
              function(res) {
                $scope.currentResources = ApplicationFactory.resources.applications;
                gaDomUtils.hideGlobalLoader();
                $scope.dialog.close();
                AlertHpoFactory.getSimpleSuccess(
                  $filter('translate')('hpo.common.success'),
                  $filter('translate')(
                    'mapv2.admin.configurationpage.cartev2transformsuccess'
                  ),
                  true,
                  'info'
                );
              },
              function(error) {
                AlertHpoFactory.showErrorMessage(error.data.message);
                gaDomUtils.hideGlobalLoader();
              }
            );
          } else {
            gaDomUtils.hideGlobalLoader();
          }
        },
        function(res) {
          AlertHpoFactory.showErrorMessage(res);
          gaDomUtils.hideGlobalLoader();
        }
      );
    };

    $scope.initApp = function(datastore, manipulate_data, multicritere) {
      if (datastore) {
        $scope.CarteConfig.datastoreuid = datastore.uid;
        $scope.CarteConfig.datastoreName = datastore.name;
        $scope.CarteConfig.dbmutualise = datastore.dbmutualise;
        $scope.CarteConfig.manipulate_data = manipulate_data;
        $scope.CarteConfig.multicritere = multicritere;
        $scope.updateConfig();
      }
    };

    $scope.upgradetomapv2 = function() {
      $scope.CarteConfig = {};
      $scope.isConfigDone = false;
      DataStoreFactory.get().then(
        function(res) {
          if (res && res.data) {
            $scope.datastores = res.data;
            $scope.initDatastore = undefined;
            $scope.multicritere = false;
            $scope.dialog = ngDialog.open({
              template:
                'js/XG/widgets/mapappv2/main/views/controller/config.html',
              className: 'ngdialog-theme-plain width800 configHpo',
              closeByDocument: false,
              title: $filter('translate')('hpo.init.datastore'),
              scope: $scope,
            });
          }
        },
        function(res) {
          AlertHpoFactory.showErrorMessage(res);
        }
      );
    };

    $scope.configmapv2 = function() {
      $scope.CarteConfig = {};
      $scope.isConfigDone = false;
      DataStoreFactory.get().then(
        function(res) {
          if (res && res.data) {
            $scope.datastores = res.data;
            ConfigFactory.get(
              'main',
              'appconfig',
              $scope.edit_resource.name
            ).then(
              function(res) {
                $scope.CarteConfig = res.data;
                if ($scope.CarteConfig && $scope.CarteConfig.datastoreuid) {
                  var idx = $scope.datastores
                    .map(function(x) {
                      return x.uid;
                    })
                    .indexOf($scope.CarteConfig.datastoreuid);
                  if (~idx) $scope.initDatastore = $scope.datastores[idx];
                  else {
                    $scope.initDatastore = undefined;
                  }
                } else {
                  $scope.initDatastore = undefined;
                }
                if (
                  $scope.CarteConfig &&
                  angular.isDefined($scope.CarteConfig.multicritere)
                )
                  $scope.multicritere = $scope.CarteConfig.multicritere;
                else {
                  $scope.multicritere = false;
                }
                $scope.dialog = ngDialog.open({
                  template:
                    'js/XG/widgets/mapappv2/main/views/controller/config.html',
                  className: 'ngdialog-theme-plain width800 configHpo',
                  closeByDocument: false,
                  title: $filter('translate')('hpo.init.datastore'),
                  scope: $scope,
                });
              },
              function(res) {
                AlertHpoFactory.showErrorMessage(res);
              }
            );
          }
        },
        function(res) {
          AlertHpoFactory.showErrorMessage(res);
        }
      );
    };

    /**
         EditList Directive configuration
         */
    $scope.editListCfg = {
      dataModule: 'applications',
      resource_type: 'applications',
      cols: ['name', 'type'],
      removeFunction: $scope.removeApplication,
      extraActions: [
        {
          icon: '<i class=\'fa fa-arrow-circle-right\'></i>',
          fn: $scope.goToApplication,
        },
        {
          label: 'applications.applications.goto_cfg',
          fn: $scope.goToCfg,
        },
      ],
      restrictAdd: {
        condition: $rootScope.xgos.isSuperAdmin ? false : true,
        message: 'applications.applications.sroot_only',
      },
      extraGlobalActions: [],
    };

    if ($rootScope.xgos.isroot) {
      $scope.editListCfg.extraGlobalActions = [
        {
          label: 'mapv2.admin.configurationpage.cartev2transform',
          fn: $scope.upgradetomapv2,
          hideFn: $scope.disableupgradetomapv2,
        },
        {
          label: 'mapv2.admin.configurationpage.conf',
          fn: $scope.configmapv2,
          hideFn: $scope.disableconfigmapv2,
        },
      ];
    }

    // check if the name is correct
    $scope.validForm = {};
    $scope.validFields = {};

    $scope.validateName = function() {
      // if copy app is enabled, duplicate this to validateCopyName
      var actualName = $scope.edit_resource.name;

      var regTab = [];
      for (
        var i = Object.keys($scope.currentResources).length - 1;
        i >= 0;
        i--
      ) {
        regTab.unshift(new RegExp($scope.currentResources[i].name, 'i'));
      }
      // console.log(regTab);
      $scope.$watch(
        'edit_resource.name',
        function(name) {
          $timeout(function() {
            $scope.nameExists = false;
            for (
              var i = Object.keys($scope.currentResources).length - 1;
              i >= 0;
              i--
            ) {
              //  console.log(Object.keys($scope.currentResources[i]));
              if (
                angular.isDefined(name) &&
                name != '' &&
                name != null &&
                name.length == $scope.currentResources[i].name.length
              ) {
                for (var i = regTab.length - 1; i >= 0; i--) {
                  if (name.match(regTab[i])) {
                    $scope.nameExists = true;
                  }
                }
              }
            }
            //Old compare
            //$scope.nameExists = $scope.currentResources.map(function(r){ return r.name; }).match(testInsensitiveTitle)!=-1;
            //$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 && $scope.validFields.name;
          });
        },
        1
      );
    };

    // check if the copy_app_name is correct
    $scope.copy_app = {};
    $scope.validCopyForm = {};
    $scope.validateCopyName = function() {
      var actualName = $scope.copy_app.name;
      $scope.$watch(
        'copy_app.name',
        function(name) {
          $timeout(function() {
            $scope.newNameExists =
              $scope.currentResources
                .map(function(r) {
                  return r.name;
                })
                .indexOf(name) != -1;
            if (!$scope.isNewResource && $scope.copy_app.name == actualName)
              $scope.namnameExistseExists = false;
            $scope.validCopyForm.name =
              !$scope.newNameExists && $scope.validFields.name;
          });
        },
        1
      );
    };

    $scope.showAlertLicence = function() {
      $rootScope.$broadcast('ngDialog.close.edit');
      swal({
        title: $filter('translate')('reject.user.nolicenceAttention'),
        text: $filter('translate')('reject.user.licence.nbapplication'),
        type: 'error',
        showCancelButton: false,
        confirmButtonColor: '#CCC',
        confirmButtonText: $filter('translate')('common.yes'),
        closeOnConfirm: true,
      });
    };

    $scope.$on('data_modal', function(event, args) {
      if (!$scope.edit_resource.type) {
        $scope.edit_resource.type = 'MapApp';

        // KIS-2844: active l'affichage du sélecteur de modèle de carte
        // à la création d'une nouvelle application de type MAP
        if (!$scope.edit_resource.params) {
          $scope.edit_resource.params = {};
        }
        $scope.edit_resource.params.mapModelSelector = true;
      }

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

    /**
     * app type anc and bac unique
     */
    $scope.$watch(
      'edit_resource.type',
      function(type) {
        $scope.typeExists = false;
        if (
          type &&
          (type == 'AncApp' || type == 'BacApp') &&
          $scope.editModalIsNew
        ) {
          $scope.typeExists =
            $scope.currentResources
              .map(function(r) {
                return r.type;
              })
              .indexOf(type) != -1;
        }
      },
      1
    );

    /*
     * ----------------------------------------------------------
     *
     * GESTION DES ECHELLES SELECTIONNABLE SUR LA CARTE
     *
     */

    $scope.appTypeIsMap = function() {
      return (
        $scope.edit_resource.type == 'MapApp' ||
        $scope.edit_resource.type == 'MapAppV2'
      );
    };

    /*
     * ----------------------------------------------------------
     *
     * type de l'application est HPO
     *
     */

    $scope.appTypeIsHpO = function() {
      return $scope.edit_resource.type == 'HpoApp';
    };

    /**
     *     L'utilisateur a cliqué sur le bouton "Echelles de carte"
     *  afin de modifier la liste de échelles de l'application.
     *  Ouverture de la fenêtre de dialogue permettant de modifier
     *  la liste des échelles sélectionnables sur la carte.
     */
    $scope.showScaleManager = function() {
      $scope.scaleMgrDlg = ngDialog.open({
        template:
          'js/XG/modules/applications/views/modals/modal.applications.scalemgr.html',
        className: 'ngdialog-theme-plain width800 nopadding miniclose',
        closeByDocument: false,
        scope: $scope.scaleMgr.scope,
      });
    };

    /**
     *  Liste les échelles de la liste des échelles de l'application
     * sous forme de chaîne de catactères afin d'être affiché
     * dans la commande d'affichage de la fenêtre de modification
     * de la liste des échelles.
     * Deux listes sont fabtiquées une tronquée pour le texte de la commande
     * et l'autre complète pour la bulle d'aide de la commande.
     */
    $scope.setScaleString = function() {
      var ind;
      $scope.scaleListAsString = '';
      $scope.fullScaleListAsString = '';
      for (ind = 0; ind < $scope.scaleMgr.scales.length; ind++) {
        if (ind < 6) {
          if ($scope.scaleListAsString != '') $scope.scaleListAsString += ',';
          $scope.scaleListAsString += $scope.scaleMgr.scales[ind].scaleValue;
        }
        if ($scope.fullScaleListAsString != '')
          $scope.fullScaleListAsString += ',';
        $scope.fullScaleListAsString += $scope.scaleMgr.scales[ind].scaleValue;
      }
      if ($scope.scaleMgr.scales.length > 6) $scope.scaleListAsString += ',...';
    };

    $scope.cleanResScaleList = function() {
      var ind;
      if ($scope.edit_resource.mapScales4Selection != undefined) {
        for (
          ind = $scope.edit_resource.mapScales4Selection.length - 1;
          (ind = 0);
          ind--
        ) {
          if ($scope.edit_resource.mapScales4Selection[ind] == null)
            $scope.edit_resource.mapScales4Selection.splice(ind, 1);
        }
      }
    };

    $scope.loadScalesFromApp = function() {
      var scales0, ind;

      if ($scope.scaleMgr.scales.length != 0)
        $scope.scaleMgr.scales.splice(0, $scope.scaleMgr.scales.length);

      if ($scope.edit_resource != undefined) {
        $scope.cleanResScaleList();
        if (
          $scope.edit_resource.mapScales4Selection == undefined ||
          $scope.edit_resource.mapScales4Selection.length == 0
        )
          $scope.edit_resource.mapScales4Selection = [
            500,
            1000,
            2000,
            10000,
            50000,
            100000,
          ];
        scales0 = $scope.edit_resource.mapScales4Selection;
        for (ind = 0; ind < scales0.length; ind++)
          $scope.scaleMgr.scales.push({
            scaleId: ind + 1,
            scaleValue: scales0[ind],
          });
        if ($scope.edit_resource.displayScaleTool == undefined)
          $scope.edit_resource.displayScaleTool = 'yes';
        $scope.scaleMgr.showScaleTool = $scope.edit_resource.displayScaleTool;
        if (
          $scope.edit_resource.wmswfs == undefined ||
          $scope.edit_resource.wmswfs == null
        ) {
          $scope.edit_resource.wmswfs = 'no';
        }
      }
    };
    $scope.loadWmsWfsAcces = function() {
      if ($scope.edit_resource != undefined) {
        if ($scope.edit_resource.wmswfs == undefined)
          $scope.edit_resource.wmswfs = 'no';
      }
    };

    $scope.saveScalesToApp = function() {
      var scales, ind;

      scales = $scope.scaleMgr.scales;
      if ($scope.edit_resource.mapScales4Selection == undefined)
        $scope.edit_resource.mapScales4Selection = [];
      else
        $scope.edit_resource.mapScales4Selection.splice(
          0,
          $scope.edit_resource.mapScales4Selection.length
        );
      for (ind = 0; ind < scales.length; ind++)
        $scope.edit_resource.mapScales4Selection.push(scales[ind].scaleValue);
      $scope.edit_resource.displayScaleTool = $scope.scaleMgr.showScaleTool;
    };

    $scope.removeScaleFromScaleList = function(res) {
      $scope.scaleMgr.scales.splice(res, 1);
    };

    $scope.initScaleManagement = function() {
      $scope.scaleMgr = {};
      $scope.scaleMgr.scope = $scope.$new(false, $scope);
      $scope.scaleMgr.scales = [];
      $scope.scaleMgrCfg = {
        dataModule: 'applications',
        resource_type: 'scalemgr.scale',
        resource_name: 'scale',
        cols: ['scaleValue'],
        currentResources: $scope.scaleMgr.scales,
        removeFunction: $scope.removeScaleFromScaleList,
        addResourceButton: true,
        deleteResourceButton: true,
        allowReorder: true,
      };

      $scope.$watch('edit_resource', $scope.loadScalesFromApp);
      $scope.$watchCollection('scaleMgr.scales.length', $scope.setScaleString);
    };
    $scope.initWmsWfsAcces = function() {
      $scope.$watch('edit_resource', $scope.loadWmsWfsAcces);
    };
    //        $scope.scaleMgr.scope.scales = [];
    //        $scope.loadScalesFromApp ();

    $scope.addScale = function(isNewRes, res) {
      var ind,
        sid = $scope.scaleMgr.scales.length + 1;
      var sidOk = false;
      var scales = $scope.scaleMgr.scales;

      if (!isNewRes)
        //-- Mise à jour d'une valeur existante.
        for (ind = 0; ind < scales.length; ind++) {
          if (scales[ind].scaleId == res.scaleId) {
            scales[ind].scaleValue = res.scaleValue;
            return;
          }
        }
      else {
        //-- Ajout d'une valeur d'échelle.
        //---- Est-ce que cette valeur existe déjà ?
        for (ind = 0; ind < scales.length; ind++) {
          if (scales[ind].scaleValue == res.scaleValue) {
            //-- La valeur d'échelle existe déjà, donc
            //-- on ne l'ajoute pas et on affiche un message
            //-- pendant quelques secondes.'
            $scope.scaleMgr.scope.valueAlreadyInList = true;
            $timeout(function() {
              $scope.scaleMgr.scope.valueAlreadyInList = false;
            }, 2000);
            return;
          }
        }
        //-- La valeur n'est pas pré-existante, donc on l'ajoute.
        while (!sidOk) {
          sidOk = true;
          for (ind = 0; ind < scales.length; ind++)
            if (scales[ind].scaleId == sid) {
              sid++;
              sidOk = false;
              break;
            }
        }
        $scope.scaleMgr.scales.push({
          scaleId: sid,
          scaleValue: res.scaleValue,
        });
      }
    };

    $scope.initScaleManagement();
    $scope.initWmsWfsAcces();

    /*
     * ----------------------------------------------------------------
     */
  };

  ApplicationCtrl.$inject = [
    '$scope',
    '$window',
    '$location',
    'ApplicationFactory',
    'RolesFactory',
    'ngDialog',
    '$timeout',
    '$filter',
    'FunctionFactory',
    '$http',
    'licenceFactory',
    '$rootScope',
    '$interval',
    'DataStoreFactory',
    'CarteAppFactory',
    'AlertHpoFactory',
    'gaDomUtils',
    'ConfigFactory',
    'SridFactory',
    'PortalsFactory'
  ];
  return ApplicationCtrl;
});
