'use strict';
define(function() {
  var portalArcgisConfig = function (FeatureTypeFactory, ngDialog, $filter,
    gaDomUtils
  ) {
    return {
      restrict: 'EA',
      scope: {
        esriIdField: '=',
        portalid: '='
      },
      link: function(scope) {

        let idDialog;
        scope.draft = {
          id: ''
        };

        /**
         *
         */
        scope.openDefineArcgisIdDialog = () =>{
          scope.attributeNotCompliant = false;
          idDialog = ngDialog.open({
            template:
                'js/XG/modules/portals/views/modals/modal.arcgis.defineid.html',
            className: 'ngdialog-theme-plain',
            closeByDocument: false,
            scope: scope,
          });
        };

        /**
         * Au clic sur le bouton "Annuler"
         * ré-initialise le champ identifiant (i.e globalid)
         */
        scope.cancelDraftEsriIdField = () => {
          closeIdDialog();
        };

        /**
         * Vérifie la compatibilité du nom de champ saisi
         *
         */
        scope.saveDraftEsriIdField = () => {
          if (scope.draft.id && scope.draft.id.length > 0) {
            gaDomUtils.showGlobalLoader();
            FeatureTypeFactory.integerAttributeExistsInArcgisFeatures(scope.portalid, scope.draft.id).then(
              res => {
                gaDomUtils.hideGlobalLoader();
                if (!res.data) {
                  /*// modifie la classe de l'input (bordure rouge)
                    scope.attributeNotCompliant = true;*/
                  swal({
                    title: $filter('translate')('portals.arcgis.popup.errortitle'),
                    text: $filter('translate')('portals.arcgis.popup.errortext') + scope.draft.id +
                    '. L’objectid sera donc utilisé pour ces champs.',
                    type: 'info'
                  });
                }
                scope.esriIdField = scope.draft.id;
                closeIdDialog();
              },
              () => {
                gaDomUtils.hideGlobalLoader();
                require('toastr').error($filter('translate')('portals.arcgis.servererror') + scope.esriIdField.id);
              }
            );
          }
        };

        const closeIdDialog = () => {
          if (idDialog){
            idDialog.close();
          }
        }

      },
      templateUrl:
          'js/XG/modules/portals/views/directives/portalArcgisConfig.html',
    };
  };

  portalArcgisConfig.$inject = ['FeatureTypeFactory', 'ngDialog', '$filter',
    'gaDomUtils'
  ];
  return portalArcgisConfig;
});
