'use strict';
define(function () {
  var ConfigFactory = function ($http, $location, $q) {
    var ConfigFactory = {};
    /**
     * Class : ConfigFactory
     * Factory WebServices
     */
    var resources = {configs: []};

    let portalid = angular.module('gcMain').portalid;
    if (portalid === undefined || portalid === '' || portalid == null) {
      portalid = localStorage.getItem('portal');
    }
    const appName = localStorage.getItem('app');

    /**
     * Function: add
     */
    function add(senddata, type, name, appname) {
      var url = appname
        ? '/services/{portalid}/config/' +
        appname +
        '/add?f=json&type=' +
        type +
        '&name=' +
        name
        : '/services/{portalid}/config/{appname}/add?f=json' +
        '&type=' +
        type +
        '&name=' +
        name;
      return $http.post(url, senddata);
    }

    /**
     * Permet d'ajouter un fichier de tout type en configuration
     * @param senddata
     * @param type
     * @param name
     * @param appname
     */
    const addFile = (senddata, type, name, fileName, oldFileName, appname) => {
      return $http.post(
          appname ?
              '/services/{portalid}/config/' + appname
              + '/addFile?f=json&type=' + type
              + '&name=' + name
              + '&fileName=' + fileName
              + '&oldFileName=' + oldFileName
          : '/services/{portalid}/config/{appname}/addFile?f=json'
              + '&type=' + type
              + '&name=' + name
              + '&fileName=' + fileName
              + '&oldFileName=' + oldFileName,
      senddata);
    };

    /**
     * Permet de télécharger un fichier de tout type en configuration
     * @param senddata
     * @param type
     * @param name
     * @param appname
     */
    const getFileUrl = (type, name, fileName, appname) => {
      return    appname ?
              '/services/' + portalid + '/config/' + appname
              + '/getFile?f=json&type=' + type
              + '&name=' + name
              + '&fileName=' + fileName
              : '/services/' + portalid + '/config/' + appName + '/getFile?f=json'
              + '&type=' + type
              + '&name=' + name
              + '&fileName=' + fileName
    };

    /**
     * Function: remove
     */
    function remove(type, name, appname) {
      var url = appname
        ? '/services/{portalid}/config/' +
        appname +
        '/remove?f=json' +
        '&type=' +
        type +
        '&name=' +
        name
        : '/services/{portalid}/config/{appname}/remove?f=json' +
        '&type=' +
        type +
        '&name=' +
        name;
      return $http.get(url);
    }

    const getGetUpdateURL = (type, name, appname, httpVerb) => {
      if (typeof ancAppAndroid !== 'undefined') {
        return $q.when(['detail', 'simple']);
      } else {
        if (appname == undefined) {
          if ($location.search().app) {
            appname = $location.search().app;
          } else {
            appname = angular.module('gcMain').app;
          }
        }
        return appname
          ? '/services/{portalid}/config/' +
          appname +
          '/' +
          httpVerb +
          '?f=json' +
          '&type=' +
          type +
          '&name=' +
          name
          : '/services/{portalid}/config/{appname}/get?f=json' +
          '&type=' +
          type +
          '&name=' +
          name;
      }
    };

    /**
     * get
     * @param type
     * @param name
     * @param appname - optional
     * @returns {HttpPromise}
     */
    const get = (type, name, appname) => {
      const url = getGetUpdateURL(type, name, appname, 'get');
      return $http.get(url);
    };

    /**
     * put
     * @param type
     * @param name
     * @param appname - optional
     * @returns {HttpPromise}
     */
    const updateConfigWithCreateCommune = (data, type, name, appname,
                                           isancapp) => {
      let url = getGetUpdateURL(type, name, appname, 'put');
      url = url + '&isancapp=' + isancapp;
      return $http.put(url, data);
    };

    /**
     * checkDocumentsForConfig -  calls the webservice which checks if the documents
     *                            found in the configuration exist on the server
     * @param controleConfig - the controle configuration object
     * @returns {HttpPromise} - the response contains the sent object with the
     *                          information about the files existence added to
     *                          the documents
     */
    function checkDocumentsForConfig(controleConfig) {
      let url = '/services/{portalid}/config/{appname}/checkDocumentsForConfig';
      return $http.post(url, controleConfig);
    }

    /**
     * checkTemplates - calls the webservice which checks if the documents
     *                  attached to the templates exist on the server
     * @param templates - the templates list
     * @returns {HttpPromise} - the response contains the sent list with the
     *                          information about the files existence added to
     *                          the templates
     */
    function checkTemplates(templates) {
      var url = '/services/{portalid}/config/{appname}/checkTemplates';
      return $http.post(url, templates);
    }

    /**
     * getAllFormCfg
     * @param type
     * @param appname - optional
     * @returns {HttpPromise}
     */
    function getAllFormCfg(type, appname) {
      if (typeof cfgandroid !== 'undefined') {
        var defer = $q.defer();
        var response = {
          data: undefined,
        };
        var value;
        var val = cfgandroid.getAllFormCfg();
        try {
          value = JSON.parse(val);
        } catch (e) {
          e.stack;
          value = val;
        }
        response.data = value;
        defer.resolve(response);
        return defer.promise;
      } else {
        var url = appname
          ? '/services/{portalid}/config/' +
          appname +
          '/getAllFormCfg?f=json' +
          '&type=' +
          type
          : '/services/{portalid}/config/{appname}/getAllFormCfg?f=json'
          +
          '&type=' +
          type;
        return $http.get(url);
      }
    }

    /**
     * gettype
     * @param appname - optional
     * @returns {HttpPromise}
     */
    function gettype(appname) {
      var url = appname
        ? '/services/{portalid}/config/' + appname + '/gettype'
        : '/services/{portalid}/config/{appname}/gettype';
      return $http.get(url);
    }

    /**
     * Function: gettype
     * @param type
     * @param appname - optional
     * @returns {HttpPromise}
     */
    function getbytype(type, appname) {
      var url = appname
        ? '/services/{portalid}/config/' + appname + '/getbytype/?type='
        + type
        : '/services/{portalid}/config/{appname}/getbytype/?type='
        + type;

      return $http.get(url);
    }

    /**
     * Function: update
     */
    function update(senddata, type, name) {
      var promise = $http.post(
        '/services/{portalid}/config/{appname}/update?f=json' +
        '&type=' +
        type +
        '&name=' +
        name,
        senddata
      );
      promise.then(function (res) {
        resources.configs.push({
          type: type,
          name: name,
          config: res.data,
        });
      });
      return promise;
    }

    /**
     * Function: getFormBuilderList
     */
    function getFormBuilderList() {
      return $http.get(
        '/services/{portalid}/config/getFormBuilderList?f=json');
    }

    /**
     * Function: reprojectExtend
     */
    function reprojectExtend(srid, type, name, appname) {
      var url = appname
        ? '/services/{portalid}/config/' +
        appname +
        '/reprojectExtend?f=json&type=' +
        type +
        '&srid=' +
        srid +
        '&name=' +
        name
        : '/services/{portalid}/config/{appname}/reprojectExtend?f=json'
        +
        '&type=' +
        type +
        '&srid=' +
        srid +
        '&name=' +
        name;
      return $http.get(url);
    }

    /**
     * Récupère les liens wiki personnalisés définis pour les widgets d'une l'application
     * @returns {Promise} promise contenant un objet dont les propriétés ont pour clé le nom du widget et l'URL du wiki en valeur
     * L'objet contient autant de propriétés que le nombre de liens wiki personnalisés existant
     */
    const getWikiConfig = () => {
      return $http.get('/services/{portalid}/config/{appname}/getWiki?f=json');
    };

    return {
      ConfigFactory: ConfigFactory,
      add: add,
      addFile: addFile,
      getFileUrl: getFileUrl,
      remove: remove,
      get: get,
      checkDocumentsForConfig: checkDocumentsForConfig,
      checkTemplates: checkTemplates,
      getAllFormCfg: getAllFormCfg,
      gettype: gettype,
      getbytype: getbytype,
      update: update,
      getFormBuilderList: getFormBuilderList,
      reprojectExtend: reprojectExtend,
      updateConfigWithCreateCommune: updateConfigWithCreateCommune,
      getWikiConfig: getWikiConfig
    };
  };

  ConfigFactory.$inject = ['$http', '$location', '$q'];
  return ConfigFactory;
});
