'use strict';
define(function() {
  /**
   * Class : ChoixProgrammeFactory
   * Factory WebServices
   */
  var ChoixProgrammeFactory = function(
    $http,
    FeatureTypeFactory,
    gaUrlUtils,
    QueryFactory
  ) {
    var resources = { config: null, descField: null, objectId: null };

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

    function getProgrammes(tableUid, where) {
      if (where == undefined) where = '';
      //where = gaUrlUtils.encodeUriQuery (where|| '');
      //var promise = $http.get('/services/{portalid}/query/'+tableUid+'/data?where='+where+'&fid='+tableUid);
      var promise = QueryFactory.data(
        tableUid,
        where,
        undefined,
        undefined,
        undefined,
        undefined
      );
      promise.then(function(res) {
        resources.programmes = res.data;
      });
      return promise;
    }

    /**
     * Function: add
     */
    function addObject(fid, senddata, featureType) {
      var features, ind1;

      //-- Build GeoJSON object describing the object we want  to insert
      features = {};
      features.type = 'FeatureCollection';
      features.features = [];
      for (ind1 = 0; ind1 < senddata.length; ind1++) {
        features.features[ind1] = {};
        features.features[ind1].type = 'feature';
        features.features[ind1].properties = senddata[ind1];
        features.features[ind1].geometry = {};
      }

      //-- Do the insert
      var promise = $http.post(
        '/services/{portalid}/edit/' + fid + '/add?f=json',
        features
      );
      promise.then(function(res) {
        var indPt;
        //- If the service returns OK (which does not mean the creation is OK)
        if (res.status == 200) {
          var created = res.data.create[0];
          if (created != undefined && created.id != undefined) {
            indPt = created.id.indexOf('.');
            resources.objectId = created.id.substr(indPt + 1);
          }
        }
      });
      return promise;
    }

    return {
      ChoixProgrammeFactory: ChoixProgrammeFactory,
      getConfig: getConfig,
      addObject: addObject,
      getProgrammes: getProgrammes,
      resources: resources,
    };
  };

  ChoixProgrammeFactory.$inject = [
    '$http',
    'FeatureTypeFactory',
    'gaUrlUtils',
    'QueryFactory',
  ];
  return ChoixProgrammeFactory;
});
