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

    /**
     * Function: get
     */
    function filterFeatureList(list, filter) {
      return $filter('filter')(list, filter);
    }

    /**
     * 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 {
      TableSelectAndUpdateFactory: TableSelectAndUpdateFactory,
      filterFeatureList: filterFeatureList,
      addObject: addObject,
      getObject: getObject,
      resources: resources,
    };
  };

  TableSelectAndUpdateFactory.$inject = [
    '$http',
    '$filter',
    '$timeout',
    'FeatureTypeFactory',
    'QueryFactory',
  ];
  return TableSelectAndUpdateFactory;
});
