'use strict';

app.service('Requests', function ($q, $http, baseUrl) {
  

  this.submitOne = function(req) {
    var d = $q.defer();

    var request = angular.copy(req);


    _.forEach(request.rooms, function (room) {
      var deviceIds = _.pluck(room.devices, 'id');
      delete room.id;

      if (room.main.punch !== -1) {
        room.main.punch = _.contains(deviceIds, room.main.punch) ? deviceIds.indexOf(room.main.punch):-1;
      }

      _.forEach(room.bstations, function (bstation) {
        delete bstation.id;
      });

      _.forEach(room.devices, function (device) {
        delete device.id;
        if (device.attr.punch !== -1) {
          device.attr.punch = _.contains(deviceIds, device.attr.punch) ? deviceIds.indexOf(device.attr.punch):-1;
        }

        //Activities array manipulation
        var len = device.activities.length;
        while (len--) {
          var activity = device.activities[len];
          if (_.contains(deviceIds, activity.device)) {
            //If device still exists after submission, replace property with index
            activity.device = deviceIds.indexOf(activity.device);
          } else {
            //If device does not exist, remove from activities array
            device.activities.splice(len,1);
          }
        }
      }); 

     delete room.activityDevices;
    });
    console.log(request);

    var json = JSON.stringify({data: request});

    $http.post(baseUrl+'/submit/create', json).success(function(response) {
      if (response.result) {
        d.resolve(response.jobId);
      } else {
        d.reject(response.error);
      }
    }).error(function(data, status, headers, config) {
      var error = status;
      if (status === 500) {
        error +=' Internal Server Error: The server encountered an unexpected condition which prevented it from fulfilling the request.';
      }
      d.reject(error);
    });

    return d.promise;
  };

  this.get = function(type, options) {
    var d = $q.defer();
    var data = { searchType: type };
    if (options) {
      angular.extend(data, options);
    }
    var json = JSON.stringify(data);

    $http.post(baseUrl+'/system/list', json).success(function(response) {
      if (response.result) {
        d.resolve(response.data);
      } else {
        d.reject(response.error);
      }
    }).error(function(error) {
      d.reject(error);
    });

    return d.promise;
  };

});