'use strict';
define(function() {
  var elasticFilterResultCfg = function($timeout) {
    return {
      scope: {
        relations: '=',
        resultsConfiguration: '=',
        updateDashboard: '=?'
      },
      templateUrl:
        'js/XG/widgets/utilities/elastic/views/elastic_filter_result_cfg.html',
      restrict: 'EA',
      link: function(scope, element, attrs, ctrl) {
        var dndrop;

        dndrop = dragula([document.getElementById('colOrdering')], {
          ignoreInputTextSelection: true,
        }).on('drop', function(el, container, source) {
          // reorder elements
          var identifiant = el.attributes['data-identifiant'].nodeValue;
          var currIndex = scope.resultsConfiguration.attributes
            .map(function(x) {
              return x.identifiant;
            })
            .indexOf(identifiant);
          var newIndex = [].slice.call(container.children).indexOf(el);

          $timeout(function() {
            scope.resultsConfiguration.attributes.splice(
              newIndex,
              0,
              scope.resultsConfiguration.attributes.splice(currIndex, 1)[0]
            );
          });
        });

        /**
         * getSelectedAttributesList
         * @param {*} x
         */
        var getSelectedAttributesList = function(x) {
          var sel = {
            attributes: [],
            ftis: [],
          };

          for (var i in x) {
            // val

            var estControleAncBac =
              ['kis_anc_dossier_controle', 'kis_bac_dossier_controle'].indexOf(
                x[i].fti.name
              ) !== -1;

            x[i].fti.attributes.map(function(a) {
              if (a.selected) {
                var _fti = x[i].fti.name;
                //if(estControleAncBac & a.alias.indexOf("json_")==0){
                if (estControleAncBac & a.isCtrJsonAttribute) {
                  _fti += '_reponse';
                }
                sel.attributes.push({
                  identifiant: _fti + '.' + a.name,
                  fti: _fti,
                  ftiAlias: x[i].fti.alias,
                  name: a.name,
                  alias: a.alias,
                  newAlias: a.alias,
                  displayAlias: a.isCtrJsonAttribute
                    ? a.prefixedAlias
                    : a.alias,
                });
              }
            });
            sel.ftis.push(x[i].fti.alias);
            // rec
            if (x[i].filters && x[i].filters.length) {
              var subSel = getSelectedAttributesList(x[i].filters);
              sel.attributes = sel.attributes.concat(subSel.attributes);
              sel.ftis = sel.ftis.concat(subSel.ftis);
            }
          }

          return sel;
        };

        if (!angular.isDefined(scope.resultsConfiguration.sort)) {
          scope.resultsConfiguration.sort = {
            order: 'asc',
          };
        }

        var set = function(force) {
          var relations = scope.relations;

          if (angular.isDefined(relations)) {
            var data = getSelectedAttributesList(relations);
            console.log(data.attributes);

            scope.usedFtis = data.ftis;

            if (
              !angular.isDefined(scope.resultsConfiguration.attributes) ||
              force
            ) {
              scope.resultsConfiguration.attributes = data.attributes;
            } else {
              // update ! @todo
              // pour chaque configuration precedente, on la garde
              if (Array.isArray(scope.resultsConfiguration.attributes)) {
                var newAttributes = [],
                  posToRemove = [],
                  newAttributesIdentifiants = data.attributes.map(function(a) {
                    return a.identifiant;
                  });

                scope.resultsConfiguration.attributes.map(function(x) {
                  // colonne deja configure
                  var newPos = newAttributesIdentifiants.indexOf(x.identifiant);
                  if (~newPos) {
                    newAttributes.push(x);
                    posToRemove.push(newPos);
                  }
                });

                posToRemove.sort(function(a, b) {
                  return b - a;
                });
                // remove to les elements deja ajoutes au nouveau tableau
                var newData = angular.copy(data.attributes);
                for (var i = 0; i <= posToRemove.length - 1; i++) {
                  newData.splice(posToRemove[i], 1);
                }

                // merge avec les nouveaux pas encore configures
                if (newData.length) {
                  newAttributes = newAttributes.concat(newData);
                }
                // set du tableau mergé
                scope.resultsConfiguration.attributes = newAttributes;
              }
            }
          }
        };

        // set initial
        scope.$watch('relations', function(relations) {
          set(0);
        });

        scope.updateDashboard.update = () => {
          set(false);
        };

        scope.doResetDashboard = function() {
          set(1);
        };

        scope.getClasseAttribut = function(attr) {
          if (angular.isDefined(scope.usedFtis)) {
            return scope.usedFtis.indexOf(attr.ftiAlias);
          }
        };
      },
    };
  };

  elasticFilterResultCfg.$inject = ['$timeout'];
  return elasticFilterResultCfg;
});
