'use strict';
define(function() {
  var AncAppSearchFactory = function($http, FeatureTypeFactory, gaJsUtils) {
    var AncAppSearchFactory = undefined;
    var SearchFTI = undefined;

    function setSearchResult(r) {
      AncAppSearchFactory = r;
    }

    function getSearchResult() {
      return AncAppSearchFactory;
    }

    function setSearchFTI(r) {
      SearchFTI = r;
    }

    function getSearchFTI() {
      return SearchFTI;
    }

    /**
     * Function: saveConfig
     */
    function saveConfig(sendata) {
      var promise = $http.post(
        '/services/{portalid}/ancapp/{appname}/save/config?f=json',
        sendata
      );

      return promise;
    }

    /**
     * Function: getConfig
     */
    function getConfig() {
      var promise = $http.get(
        '/services/{portalid}/ancapp/{appname}/get/config?f=json'
      );

      return promise;
    }

    // -------------------------------------------------------------
    // Fonctions permettant de reduire la taille des objets requetes
    // -------------------------------------------------------------

    /**
     * packRequest
     * permet de stocker une version plus courte
     */
    function packRequest(extraCriterias) {
      if (angular.isDefined(extraCriterias)) {
        extraCriterias.map(function(x) {
          if (x.filter) {
            // reduction du fti
            if (x.filter.selectedfti)
              x.filter.selectedfti =
                'fti_to_retrieve:' + x.filter.selectedfti.name;
            // reduction des aliases
            if (x.filter.attributesaliases)
              x.filter.attributesaliases =
                'attributesaliases_to_retrieve:' + x.filter.selectedfti.name;
            // TODO : meme chose
            // x.filter.attr
            console.log(x);
          }
          return x;
        });
      }
    }

    /**
     * unPackRequest
     * permet de retrouver la version originale
     */
    function unPackRequest(req, datastore, fakeCtrlReponse) {
      var stringReq = JSON.stringify(req);

      // 1. FTIS
      var unpacked = stringReq.replace(/"fti_to_retrieve:(\w*)"/g, function(
        match,
        ftiName
      ) {
        var cleanName = ftiName.replace('___selected', '');

        if (cleanName == 'kis_anc_dossier_controle_reponse') {
          var fti = angular.isDefined(fakeCtrlReponse) ? fakeCtrlReponse : {};
        } else if (cleanName == 'kis_bac_dossier_controle_reponse') {
          var fti = angular.isDefined(fakeCtrlReponse) ? fakeCtrlReponse : {};
        } else if (cleanName == 'kis_anc_vidange_formulaire_reponse') {
          var fti = {
            name: 'kis_anc_vidange_formulaire_reponse',
            alias: 'vidange formulaire reponse',
            attributes: [],
          };
        } else {
          var fti = angular.copy(
            FeatureTypeFactory.getFeatureByNameAndDatastore(
              datastore,
              cleanName
            )
          );
        }

        // si fini par ___selected, selectionne tous les attributs
        if (gaJsUtils.endsWith(ftiName, '___selected')) {
          fti.attributes.map(function(attr) {
            attr.selected = true;
          });
        }
        return JSON.stringify(fti);
      });

      // 2. Attributes
      unpacked = unpacked.replace(
        /"attribute_to_retrieve:(\w*):(\w*)"/g,
        function(match, ftiName, attrName) {
          // sauf si ftiname est dossierSelected
          var fti = angular.copy(
            FeatureTypeFactory.getFeatureByNameAndDatastore(datastore, ftiName)
          );
          var attr = fti.attributes.filter(function(x) {
            return x.name == attrName;
          });
          return attr.length ? JSON.stringify(attr[0]) : '{}';
        }
      );

      // 3. attributesaliases
      var unpacked = unpacked.replace(
        /"attributesaliases_to_retrieve:(\w*)"/g,
        function(match, ftiName) {
          var fti = angular.copy(
            FeatureTypeFactory.getFeatureByNameAndDatastore(datastore, ftiName)
          );
          var attributesaliases = fti.attributes.map(function(x) {
            return x.alias;
          });
          return JSON.stringify(attributesaliases);
        }
      );

      // 3. extra_to_retrieve (extra parameter query)
      var unpacked = unpacked.replace(/"extra_to_retrieve:(\w*)"/g, function(
        match,
        extraParamIndex
      ) {
        var jsonPropre = JSON.parse(unpacked);
        var extraCriteria = angular.isDefined(
          jsonPropre.extraCriterias[extraParamIndex]
        )
          ? JSON.stringify(jsonPropre.extraCriterias[extraParamIndex].filter)
          : JSON.stringify({});
        return extraCriteria;
      });

      // force le dossier dans le statut en_cours
      let finalJSON = JSON.parse(unpacked);
      try {
        let filter = {
          choice: 'rule',
          name: 'etat_dossier',
          type: 'java.lang.String',
          att: 'État',
          operand: 'equals',
          value: 'en_cours',
          selectedfti: angular.copy(
            FeatureTypeFactory.getFeatureByNameAndDatastore(
              datastore,
              'kis_anc_dossier'
            )
          ),
        };
        if (
          finalJSON.elasticQuery.relations[0].selectGlobaladvancedFti ==
          'Vidanges'
        ) {
          filter.operand = 'include';
          filter.value = 'en_cours,ouvert,raccorde';
        }
        finalJSON.elasticQuery.relations[0].filters[0].filters.push(filter);
      } catch (error) {
        console.log('erreur ajout condition sur le statut du dossier ' + error);
      }

      return finalJSON;
    }

    return {
      AncAppSearchFactory: AncAppSearchFactory,
      setSearchResult: setSearchResult,
      getSearchResult: getSearchResult,
      setSearchFTI: setSearchFTI,
      getSearchFTI: getSearchFTI,
      saveConfig: saveConfig,
      getConfig: getConfig,

      packRequest: packRequest,
      unPackRequest: unPackRequest,
    };
  };
  AncAppSearchFactory.$inject = ['$http', 'FeatureTypeFactory', 'gaJsUtils'];
  return AncAppSearchFactory;
});
