﻿"use strict";

// Auth Interceptor service "intercepts" all requests to server and adds our auth data
app.factory("authInterceptorService", ["$q", "$injector", "$location", "localStorageService", "ngAuthSettings",
    function ($q, $injector, $location, localStorageService, ngAuthSettings) {

    var authInterceptorServiceFactory = {};
    var $http;

    var _request = function (config) {

        config.headers = config.headers || {};

        var authData = localStorageService.get(ngAuthSettings.authDataKey);
        if (authData) {
            config.headers.Authorization = 'Bearer ' + authData.token;
            config.headers.JudgeAuthorization = "Bearer" + authData.token;
        }

        return config;
    }

    var _responseError = function (rejection) {
        var deferred = $q.defer();
        if (rejection.status === 401) {
            var authService = $injector.get('authService'); // Need to manually resolve authService here or we'll get a circular dependency
            authService.refreshToken().then(function (response) {
                _retryHttpRequest(rejection.config, deferred);
            }, function () {
                authService.logOut();
                deferred.reject(rejection);
            });
        } else {
            deferred.reject(rejection);
        }
        return deferred.promise;
    }

    var _retryHttpRequest = function (config, deferred) {
        $http = $http || $injector.get('$http'); // Need to manually resolve authService here or we'll get a circular dependency
        $http(config).then(function (response) {
            deferred.resolve(response);
        }, function (response) {
            deferred.reject(response);
        });
    }

    authInterceptorServiceFactory.request = _request;
    authInterceptorServiceFactory.responseError = _responseError;

    return authInterceptorServiceFactory;
}]);
