export default class LoginController {

  constructor($http, $window, $state, HostFactory) {
    'ngInject';
    this.$http = $http;
    this.$window = $window;
    this.$state = $state;
    this.HostFactory = HostFactory;

  }

  $onInit() {
      const HOST = this.HostFactory.getHost();
      this.URL_PATH = 'http://' + HOST + '/login';
      this.isAuthenticated = false;
      this.username = 'federico@wonderflow.co';
      this.password =  'federico-wonderflow-2016';
  }

  login() {
      this.$http
          .post(this.URL_PATH, {
              username: this.username,
              password: this.password
          })
          .success((data, status, headers, config) => {
              let user;
              user = data.user || {};
              this.$window.sessionStorage.token = data.token;
              this.$window.sessionStorage.user = JSON.stringify(user);
              console.log('successfully logged in');
              this.$state.go('reviews');
          })
          .error((data, status, headers, config) => {
              // Erase the token if the user fails to log in
              delete this.$window.sessionStorage.token;
              delete this.$window.sessionStorage.user;
              // delete $localStorage.token;
              console.log(data, status, headers, config);
              // Handle login errors here
              this.username = '';
              this.password = '';
              console.log('Error: Invalid user or password');
          });

  }
}
