'use strict';
define(function() {
  var gcattribute = function(FeatureTypeFactory, $filter, $rootScope,RightsFactory) {
    return {
      templateUrl: 'js/XG/widgets/utilities/model/views/gcattribute.html',
      restrict: 'AE',
      scope: {
        result: '=?res',
        resultname: '=?resname',
        fti: '=?',
        ftid: '=?',
        attributetype: '@attributetype',
        locked: '=?', // 10/09/21 fait bugger
        attributesgranted: '=?', // liste des attributs dont l'utilisateur a les droits en écriture
        width: '@width',
        resetoption: '@resetoption',
        autocomplete: '=?'
      },
      link: function (scope) {
        scope.locked = scope.locked ? scope.locked = 'true' : false;

        //Attribut
        var tFti = null;
        scope.selectedattribut = {};
        scope.attributs = [];
        scope.myfilter = {};
        console.log(scope.attributetype);
        scope.myfilter.type = scope.attributetype;
        scope.gcAttributeStyle = {
          'max-height': '100px'
        };
        if (!scope.autocomplete) {
          //-- En cas d'autocomplete l'overflow est géré différemment
          scope.gcAttributeStyle.overflow = 'auto';
        }
        if (scope.width) {
          scope.gcAttributeStyle.width = scope.width;
        }
        else {
          scope.gcAttributeStyle.width = '250px';
        }

        scope.$watch(
          function() {
            return scope.fti;
          },
          function() {
            if (!angular.isUndefined(scope.fti)) {
              tFti = scope.fti;
              getLinkAttribute(true);
            }
          },
          true
        );

        scope.$watch(
          'fti',
          (newVal, oldVal) => {
            if (newVal && oldVal && newVal.uid != oldVal.uid){
              scope.result = undefined;
              scope.selectedattribut.val = '';
            }
          },
          1
        );

        function updateFti() {
          if (angular.isDefined(scope.ftid)) {
            var uidFound = false;
            FeatureTypeFactory.resources.featuretypes.forEach(function(f) {
              if (!uidFound && f.uid == scope.ftid) {
                tFti = f;
                getLinkAttribute(true);
                uidFound = true;
              }
            });
          }
        }

        const getLinkAttribute = (updateAttributes) => {
          if (tFti) {
            // Déterminer les droits de l'utilisateur
            let attributesGranted = [];
            if ($rootScope.xgos) {
              const isAdmin = $rootScope.xgos.isroot || $rootScope.xgos.isadmin;
              attributesGranted = RightsFactory.getUserWriteOrReadRightsAttributes(
                $rootScope.xgos.user,
                tFti,
                isAdmin,
                true
              );
            }
        
            if (updateAttributes) {
              scope.attributs = [];
            }
            for (let att of tFti.attributes) {
              // Mise à jour des sélections existantes
              if (scope.result && att.name === scope.result.name){
                scope.selectedattribut.val = att;
              } else if (scope.resultname && att.name === scope.resultname) {
                scope.result = att;
                scope.selectedattribut.val = att;
              }
              // aussi l'utilisateur doit être root ou bien avoir les droits en écriture sur l'attribut pour que celui-ci apparaissent dans la liste des attributs de la liste des données
              if (
                updateAttributes &&
                ( !attributesGranted.length ||
                  attributesGranted.some(grantedAtt => grantedAtt.name === att.name) ||
                  ($rootScope.xgos && $rootScope.xgos.isroot)
                )
              ) {
                scope.attributs.push(att);
              }
            }
          }
        };

        scope.$watch('ftid', function() {
          if (scope.ftid && !scope.fti) {
            if (FeatureTypeFactory.resources.featuretypes.length == 0) {
              FeatureTypeFactory.get().then(function(res) {
                updateFti();
              });
            } else updateFti();
          }
        });

        /*scope.fti.attributes.forEach(function (att)
            {
                 scope.attributs.push ({"value":att.name,"label":att.alias,"att":att});
            }); */

        scope.$watch('result', function(newp) {
          if (!angular.isUndefined(newp) && newp != null) {
            if (newp !== scope.selectedattribut.val) getLinkAttribute(false);
          }
        });

        scope.$watch('resultname', function(newp) {
          if (!angular.isUndefined(newp) && newp != null) {
            if (
              angular.isDefined(scope.selectedattribut.val) &&
              newp !== scope.selectedattribut.val.name
            )
              getLinkAttribute(false);
          }
        });

        scope.selectattributchange = function() {
          scope.result = scope.selectedattribut.val;
          scope.resultname = angular.isDefined(scope.selectedattribut.val)
            ? scope.selectedattribut.val.name
            : null;
          //scope.$apply();
        };

        scope.transalteAlias = function(x) {
          var alias = x.alias;
          if (
            $filter('translate')(
              'features.' + tFti.name + '.properties.' + x.name
            ).indexOf('features.') === -1
          )
            alias = $filter('translate')(
              'features.' + tFti.name + '.properties.' + x.name
            );
          return alias;
        };

        /**
         * LayerManagerWidget
         * Met à jour la liste des attributs quand arrive les noms d'attributs dont l'utilisateur a les droits en écriture
         */
        scope.$watch('attributesgranted', () => {
          getLinkAttribute(true);
        });
      },
    };
  };

  gcattribute.$inject = ['FeatureTypeFactory', '$filter', '$rootScope','RightsFactory'];
  return gcattribute;
});
