'use strict';
define(function() {
  /**
   * Class : ChercherModSupFactory
   * Factory WebServices
   */
  var ChercherModSupFactory = function(
    $http,
    FeatureTypeFactory,
    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: get
     */
    function getObject(tableUid, whereClause) {

      var promise = QueryFactory.data(
        tableUid,
        whereClause,
        undefined,
        undefined,
        undefined,
        undefined
      );
      promise.then(function(res) {
        resources.objects = res.data;
      });
      return promise;
    }

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

      //-- Build GeoJSON object describing the object we want  to insert
      features = {};
      features.type = 'FeatureCollection';
      features.features = [];
      features.features[0] = {};
      features.features[0].type = 'feature';
      features.features[0].properties = senddata;
      features.features[0].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 {
      ChercherModSupFactory: ChercherModSupFactory,
      getConfig: getConfig,
      addObject: addObject,
      getObject: getObject,
      resources: resources,
    };
  };

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