angular.module('avalancheServices.Oauth', [])
.service('OAuthService', [ '$rootScope', '$http', '$location', '$localstorage',  function($rootScope, $http, $location, $localstorage) {
  var code = {};
  //var token = "";
  //var token = $cookies.get('avalanche_docs_token');
  var token = $localstorage.get('token');
  var user = {};
  var missions = [];

  this.authorizeApplication = function(code){
    $http({
      method: 'POST',
      url: 'http://localhost:5000/oauth/token?client_id=d514f58c234d69ce1405f00dbef842bd785c09201b35a746d87306f5e69fd02b&client_secret=de63eb190485179d713df3e15339eb618e78e94ab96185621112dd0e5215997c&grant_type=authorization_code&redirect_uri=http://localhost:9000/&code=' + code
    }).then(function(data) {
      token = data.data.access_token;
      //$cookies.put('avalanche_docs_token', token);
      console.log("Application Authorization Flow SUCCESSFULL")
      console.log(data.data);
      $rootScope.$broadcast('auth:success');
    },
    function(data) {
      console.log("Application Authorization Flow FAILED")
      console.log(data);
      $rootScope.$broadcast('auth:failed');
    });
  }

  this.authorizeUser = function(username, password){
    $http({
      method: 'POST',
      url: 'http://localhost:5000/oauth/token',
      params: {
        "grant_type"    : "password",
        "username"      : username,
        "password"      : password
      }
    }).then(function(data) {
      token = data.data.access_token;
      user = data.data.user;
      missions = data.data.missions;
      //$cookies.put('avalanche_docs_token', token);
      $localstorage.set('token', token);
      $localstorage.setObject('user', data.data.user);
      $localstorage.setObject('missions', data.data.missions);
      console.log("Resource Owner Password Credentials flow SUCCESSFULL")
      console.log(data.data);
      $rootScope.$broadcast('auth:success');
    },
    function(data) {
      console.log("Resource Owner Password Credentials flow FAILED")
      console.log(data);
      $rootScope.$broadcast('auth:failed');
    });
  }

  this.getToken = function() {
    return token;
  }

  this.getUser = function() {
    return user;
  }

  this.getMissions = function() {
    return missions;
  }

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

}])
