'use strict';
define(function() {
  var elasticEditRequest = function(
    ParametersFactory,
    $rootScope,
    gaJsUtils,
    FeatureTypeFactory,
    $q
  ) {
    return {
      templateUrl:
        'js/XG/widgets/utilities/elastic/views/elastic_edit_request.html',
      restrict: 'EA',
      scope: {
        apptype: '=?',
        onSearch: '&',
        request: '=?',
        map: '=?',
        currentRequest: '=?',
        skipSearchEvent: '=?'
      },
      link: function(scope, elt, attrs, ctrl) {
        scope.visible = false;

        function getFtis() {
          if (scope.apptype != 'anc' || angular.isDefined(scope.map)) {
            var promise = FeatureTypeFactory.get();
          } else {
            var def = $q.defer();
            def.resolve();
            promise = def.promise;
          }

          promise.then(function(res) {
            // pour ANC seulement, regarder dans elastifilter.js pour avoir le code complet
            if (scope.apptype === 'anc') {
              scope.componentftis = FeatureTypeFactory.resources.featuretypes
                .map(function(x) {
                  if (
                    ([
                      'kis_anc_dossier',
                      'kis_anc_dossier_controle',
                      'kis_anc_dossier_filiere',
                    ].indexOf(x.name) !== -1 ||
                      x.name.startsWith('kis_anc_ef_')) &&
                    x.inElasticSearch
                  ) {
                    return x;
                  }
                })
                .filter(function(x) {
                  if (x) return x;
                });
            }
          });
        }
        getFtis();

        var relations = [];

        function getDeepObjectByKeyValue(obj, key, value) {
          var result = null;
          if (obj instanceof Array) {
            for (var i = 0; i < obj.length; i++) {
              result = getDeepObjectByKeyValue(obj[i], key, value);
              if (result) {
                if (
                  obj[i].hasOwnProperty('selectGlobaladvancedFti') &&
                  !angular.isDefined(relations[value])
                ) {
                  relations[value] = obj[i];
                }
                break;
              }
            }
          } else {
            for (var prop in obj) {
              if (prop == key) {
                if (obj[prop] == value) {
                  return obj;
                }
              }
              if (obj[prop] instanceof Object || obj[prop] instanceof Array)
                result = getDeepObjectByKeyValue(obj[prop], key, value);
              if (result) {
                if (
                  obj[prop].hasOwnProperty('selectGlobaladvancedFti') &&
                  !angular.isDefined(relations[value])
                ) {
                  relations[value] = obj[prop];
                }
                break;
              }
            }
          }
          return result;
        }

        scope.parameters = [];
        // verifie qu'on a au moins tenté de recup la requete, ce qui evite un affichage 0.1 sec de "Aucune requête ne portant ce nom n'a pu être retrouvée."
        scope.requeteRecuperee = false;

        if (!scope.currentRequest) {
          // recuperation de la requete
          ParametersFactory.getbyname(scope.request.name).then(function(res) {
            scope.requeteRecuperee = true;
  
            if (res.data) {
              scope.currentRequest = res.data;
              if (res.data.data.fieldsConfiguration) {
                scope.fieldsConfiguration = res.data.data.fieldsConfiguration;
                resolveParameters();
              }
            } else {
              // display some error msg
              scope.currentRequest = false;
              console.log('error');
            }
          });
        } else {
          if (scope.currentRequest.fieldsConfiguration) {
            scope.fieldsConfiguration = scope.currentRequest.fieldsConfiguration;
            resolveParameters();
          }
        }

        scope.filterId = gaJsUtils.guid();

        scope.saveAndExecuteQuery = function() {
          if (!scope.skipSearchEvent) {
            // on remplace dans la requete a envoyer a elastic
            $rootScope.$broadcast('elastic_LoadAndExecuteRequest', {
              request: scope.currentRequest.data,
              filterId: scope.filterId,
            });
          } else {
            scope.onSearch({
              result: scope.currentRequest,
            });
          }
        };

        scope.inner = {};
        scope.$watch(
          'inner',
          function(inner) {
            if (inner.res && !gaJsUtils.isEmptyObject(inner.res) ) {
              scope.onSearch({
                result: scope.inner.res,
                fti: scope.inner.res.fti,
              });
            }
          },
          1
        );

        // toggle from liste dossiers
        $rootScope.$on('toggleAllAncRequests', function(event, data) {
          scope.visible = data.v;
        });

        function resolveParameters() {
          Object.keys(scope.fieldsConfiguration).forEach(function(guid) {
            if (scope.fieldsConfiguration[guid].visible) {
              var obj = getDeepObjectByKeyValue(
                scope.currentRequest,
                'guid',
                guid
              );

              if (obj !== null)
                scope.parameters.push({
                  filter: obj,
                  relation: relations[guid],
                });
            }
          });
        }
      },
    };
  };

  elasticEditRequest.$inject = [
    'ParametersFactory',
    '$rootScope',
    'gaJsUtils',
    'FeatureTypeFactory',
    '$q',
  ];
  return elasticEditRequest;
});
