angular.module('avalancheServices.Data', [])
.service('DataService', [ '$rootScope', '$http', '$localstorage',  function($rootScope, $http, $localstorage) {
  var response = {};
  var domain = "http://localhost:5000/api"

  // GET
  this.get = function(url, inputs, token){
    console.log("Requesting data from " + url);
    console.log(inputs);
    console.log(token);
    $http({
      method: 'GET',
      url: domain + url,
      headers: { 'Authorization' : "Bearer " + token },
      params: inputs
    }).then(function(data, status, headers, config) {
      console.log("GET Request SUCCESSFULL")
      response.data = data.data;
      response.status = data.status;
      response.headers = data.headers;
      response.config = data.config;
      console.log(response)
      $rootScope.$broadcast('get-data-success:' + url);
    },
    function(data, status) {
      console.log("GET Request FAILED")
      response.data = data.data;
      response.status = data.status;
      response.headers = data.headers;
      response.config = data.config;
      console.log(response)
      $rootScope.$broadcast('get-data-failure:' + url);
    });
  }

  // POST
  this.post = function(url, inputs, token){
    console.log("Posting data to " + url);
    console.log(inputs);
    console.log(token);
    $http({
      method: 'POST',
      url: domain + url,
      headers: { 'Authorization' : "Bearer " + token },
      params: inputs
    }).then(function(data, status, headers, config) {
      console.log("POST Request SUCCESSFULL")
      response.data = data.data;
      response.status = data.status;
      response.headers = data.headers;
      response.config = data.config;
      console.log(response)
      $rootScope.$broadcast('get-data:finished');
    },
    function(data, status) {
      console.log("POST Request FAILED")
      response.data = data.data;
      response.status = data.status;
      response.headers = data.headers;
      response.config = data.config;
      console.log(response)
      $rootScope.$broadcast('get-data:finished');
    });
  }

  // RESPONSE
  this.getResponse = function() {
    return response;
  }

  this.getMission = function(slug) {
    var missions = $localstorage.getObject('missions');
    for (var i = 0; i < missions.length; i++) {
      if(missions[i].slug == slug) {
        return missions[i];
      }
    }
    return false;
  }

}])
