/* globals angular */
'use strict';

angular.module('EnterpriseDashboardApp.Authentication', [])
	.service('Authentication', function Authentication($rootScope, $q, $window) {

		// var URL_PATH;

		// HOST = HostFactory.getHost();

		// URL_PATH = 'http://' + HOST + '/login';



		var Service = {
			// login: function(username, password) {
			// $http
			// 	.post(URL_PATH, {
			// 		username: username,
			// 		password: password
			// 	})
			// 	.success(function(data) {
			// 		$window.sessionStorage.token = data.token;

			// 		$scope.message = 'Welcome';
			// 		$window.location.href = '#/';
			// 	})
			// 	.error(function(data, status, headers, config) {
			// 		// Erase the token if the user fails to log in
			// 		delete $window.sessionStorage.token;
			// 		// delete $localStorage.token;
			// 		console.log(data, status, headers, config);

			// 		// Handle login errors here
			// 		$scope.message = 'Error: Invalid user or password';
			// 		$scope.username = '';
			// 		$scope.password = '';
			// 		console.log('Error: Invalid user or password');
			// 	});
			// },
			getAuthenticationToken: function() {
				return $window.sessionStorage.token;
			},
			logout: function() {
				delete $window.sessionStorage.token;
				$window.location.href = '#/login';
			},
			checkAuthorization: function() {
				if (!$window.sessionStorage.token) {
					$window.location.href = 'login';
					return;
				}
			},
			request: function(config) {
				var token;
				config.headers = config.headers || {};

				token = $window.sessionStorage.token;
				// console.log('BEFORE REQUEST: token', token)
				if (token) {
					config.headers.Authorization = 'Bearer ' + token;
				}
				return config;
			},
			responseError: function(response) {
				// console.log('in respose method method', response.status, response);
				if (response.status === 401) {
					// handle the case where the user is not authenticated
					$window.location.href = '#/login';
					return;
				}
				return $q.reject(response);
			},
			getAuthInterceptor: function($rootScope, $q, $window) {
				return angular.factory('authInterceptor', function() {
					return {
						request: function(config) {
							var token;
							config.headers = config.headers || {};

							// token = $localStorage.token;
							token = $window.sessionStorage.token;
							// console.log('BEFORE REQUEST: token', token)
							if (token) {
								config.headers.Authorization = 'Bearer ' + token;
							}
							return config;
						},
						responseError: function(response) {
							// console.log('in respose method method', response.status, response);
							if (response.status === 401) {
								// handle the case where the user is not authenticated
								$window.location.href = '#/login';
								return;
							}
							return $q.reject(response);
						}
					};
				});
			}
		};



		return Service;
	});
