'use strict';
define(function() {
  var indigauChoixDensiteRegle = function(
    IndigauFactory,
    ngDialog,
    gaJsUtils,
    $filter
  ) {
    return {
      templateUrl:
        'js/XG/widgets/indigauapp/home_admin_data/views/directives/indigauChoixDensiteRegle.html',
      restrict: 'EA',
      scope: {},
      link: function(scope) {
        function getCarteConfigFrom(pScope) {
          if (pScope == undefined) return;
          if (pScope.CarteConfig == undefined)
            return getCarteConfigFrom(pScope.$parent);
          else return pScope.CarteConfig;
        }

        function loadIndicateurs() {
          IndigauFactory.getIndicateursAndChoixRegle(
            scope.CarteConfig.datastoreName
          ).then(function(res) {
            if (res.data.etat == 'erreur') {
              require('toastr').error(
                gaJsUtils.errorListToOneString(res.data.errorList)
              );
            } else {
              scope.indicateurs = res.data.objValeur;
            }
          });
        }

        /**
         *    Setting what is the current version in the scope.ws.selectedVersion
         * property, make the version being selected in the version selection dialog.
         */
        function setSelectedVersionFromCurIndicateur() {
          let ind, curIndicVersion, fn;

          if (scope.currentIndicateur.regle_densite == undefined) return;

          if (scope.typeOfVersions == 'regle') {
            curIndicVersion = scope.currentIndicateur.regle_densite.idregle;
            fn = 'idVersion';
          } else {
            curIndicVersion = scope.currentIndicateur.regle_densite.IDs;
            fn = 'iDSeuil';
          }

          for (ind = 0; ind < scope.versions.length; ind++) {
            if (scope.versions[ind][fn] == curIndicVersion) {
              scope.ws.selectedVersion = scope.versions[ind];
              break;
            }
          }
        }

        /**
         *    Open dialog in order to select a version.
         * The dialog content allows also to remove and to rename a version.
         */
        scope.openChoixVersion = function(indicateur, typeOfVersions) {
          IndigauFactory.getIndicateurVersions(
            typeOfVersions,
            scope.CarteConfig.datastoreName,
            indicateur.indicateur
          ).then(function(res) {
            if (res.data.etat == 'erreur') {
              require('toastr').error(
                gaJsUtils.errorListToOneString(res.data.errorList)
              );
            } else {
              scope.versions = res.data.objValeur;
              scope.typeOfVersions = typeOfVersions;
              scope.currentIndicateur = indicateur;
              setSelectedVersionFromCurIndicateur();
              scope.indigauChoixVersionDlg = ngDialog.open({
                template:
                  'js/XG/widgets/indigauapp/home_admin_data/views/dialog/indigauChoixVersion.html',
                className: 'ngdialog-theme-plain width800 miniclose nopadding',
                closeByDocument: false,
                scope: scope,
              });
            }
          });
        };

        function getSelectedVersionNames() {
          let names = '',
            ind;
          //-- Build liste of the selected "seuils" identifiers.
          for (ind = 0; ind < scope.versions.length && ind < 10; ind++) {
            if (scope.versions[ind].toRemove) {
              if (names.length != 0) names += ', ';
              names += scope.versions[ind].nomVersion;
            }
          }
          if (scope.versions.length > 10) names += ', ...';
          return names;
        }

        function getVersionIdFieldName(typeOfVersions) {
          if (typeOfVersions == 'densite') return 'iDSeuil';
          else return 'idVersion';
        }

        /**
         *     Remove action from user:
         *   -1- Ask user to confirm the removal.
         *   -2- If confirmed run the removal.
         */
        scope.removeVersion = function(typeOfVersions) {
          swal(
            {
              title: $filter('translate')(
                'indigau.admin.confirmVersionRemoval'
              ).replace('{versionNames}', getSelectedVersionNames()),
              //text: "You will not be able to recover this imaginary file!",
              type: 'warning',
              showCancelButton: true,
              confirmButtonColor: '#DD6B55',
              confirmButtonText: $filter('translate')('common.yes'),
              cancelButtonText: $filter('translate')('common.no'),
              closeOnConfirm: true,
            },
            function(isConfirmed) {
              if (isConfirmed) {
                let ids = '',
                  ind,
                  fieldName = getVersionIdFieldName(typeOfVersions);

                //-- Build liste of the selected "seuils" identifiers.
                for (ind = 0; ind < scope.versions.length; ind++) {
                  if (scope.versions[ind].toRemove) {
                    if (ids.length != 0) ids += ',';
                    ids += scope.versions[ind][fieldName];
                  }
                }
                IndigauFactory.deleteVersion(
                  typeOfVersions,
                  scope.CarteConfig.datastoreName,
                  ids
                ).then(function(res) {
                  if (res.data.etat == 'erreur') {
                    require('toastr').error(
                      gaJsUtils.errorListToOneString(res.data.errorList)
                    );
                  }
                  //-- Refresh list of version from database.
                  IndigauFactory.getIndicateurVersions(
                    typeOfVersions,
                    scope.CarteConfig.datastoreName,
                    scope.currentIndicateur.indicateur
                  ).then(function(res) {
                    if (res.data.etat == 'erreur') {
                      require('toastr').error(
                        gaJsUtils.errorListToOneString(res.data.errorList)
                      );
                    } else {
                      scope.versions = res.data.objValeur;
                      setSelectedVersionFromCurIndicateur();
                    }
                  });
                });
              }
            }
          );
        };

        /**
         *  A version has been selected, so update database indictaeur and
         * refresh user interface getting the list again.
         */
        scope.versionSelected = function(version, typeOfVersions) {
          IndigauFactory.selectIndicateurVersion(
            typeOfVersions,
            scope.CarteConfig.datastoreName,
            version[getVersionIdFieldName(typeOfVersions)],
            scope.currentIndicateur.indicateur
          ).then(function(res) {
            if (res.data.etat == 'erreur') {
              require('toastr').error(
                gaJsUtils.errorListToOneString(res.data.errorList)
              );
            } else {
              loadIndicateurs();
            }
          });
        };

        scope.saveVersion = function(version, typeOfVersions) {
          let versionId;
          if (typeOfVersions == 'densite') versionId = version.iDSeuil;
          else versionId = version.idVersion;
          IndigauFactory.updateComplementDeNom(
            typeOfVersions,
            scope.CarteConfig.datastoreName,
            versionId,
            version.nomVersion
          ).then(function(res) {
            if (res.data.etat == 'erreur') {
              require('toastr').error(
                gaJsUtils.errorListToOneString(res.data.errorList)
              );
            } else {
              version.textInputStyle = { 'background-color': '#eeeeee' };
              version.editMode = false;
            }
          });
        };

        function init() {
          //-- WorkSpace to work on main sope data from child scopes
          scope.ws = {};
          scope.colParamsVisible = false;
          scope.CarteConfig = getCarteConfigFrom(scope);
          loadIndicateurs();
        }

        init();
      },
    };
  };

  indigauChoixDensiteRegle.$inject = [
    'IndigauFactory',
    'ngDialog',
    'gaJsUtils',
    '$filter',
  ];
  return indigauChoixDensiteRegle;
});
