'use strict';

//HCM Installer Auth service

app.service('Auth', function ($http, $q, $rootScope, $timeout, $window) {

  var service = this;
  this._user = null;
  
  this.setCurrentUser = function(u) {
    console.log(u);
    service._user = u;
    $window.localStorage.setItem('hcm_installer', JSON.stringify(u));
    $rootScope.companyName = u.companyName;
    $rootScope.companyId = u.companyId;
    $timeout(function(){
      $rootScope.$broadcast('user:set', u);
    }, 500);
  };

  this.removeCurrentUser = function() {
    service._user = null;
    $window.localStorage.removeItem('hcm_installer');
    $rootScope.companyName = '';
    $rootScope.companyId = '';
    $rootScope.$broadcast('user:unset');
  };

  this.currentUser = function() {
    var d = $q.defer();
    if(service._user) {
      d.resolve(service._user);
    } else if($window.localStorage.getItem('hcm_installer')) {
      var user = JSON.parse($window.localStorage.getItem('hcm_installer'));
      console.log('setting current user');
      service.setCurrentUser(user);
      d.resolve(service._user);
    } else {
      d.resolve(null);
    }
    return d.promise;
  };
});