import { AuthService } from './secure-http/auth.service';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { AuthHttp } from 'angular2-jwt';
import 'rxjs/add/operator/catch';
var SecureHttp = (function () {
    function SecureHttp(http, authService) {
        this.http = http;
        this.authService = authService;
    }
    SecureHttp.prototype.get = function (url, options) {
        var _this = this;
        return this._makeRequest(url, function () { return _this.http.get(url, options); });
    };
    SecureHttp.prototype.post = function (url, body, options) {
        var _this = this;
        return this._makeRequest(url, function () { return _this.http.post(url, body, options); });
    };
    SecureHttp.prototype.put = function (url, body, options) {
        var _this = this;
        return this._makeRequest(url, function () { return _this.http.put(url, body, options); });
    };
    SecureHttp.prototype.delete = function (url, options) {
        var _this = this;
        return this._makeRequest(url, function () { return _this.http.delete(url, options); });
    };
    SecureHttp.prototype.patch = function (url, body, options) {
        var _this = this;
        return this._makeRequest(url, function () { return _this.http.patch(url, options); });
    };
    SecureHttp.prototype.head = function (url, options) {
        var _this = this;
        return this._makeRequest(url, function () { return _this.http.head(url, options); });
    };
    SecureHttp.prototype.options = function (url, options) {
        var _this = this;
        return this._makeRequest(url, function () { return _this.http.options(url, options); });
    };
    SecureHttp.prototype._makeRequest = function (resource, makeRequest) {
        var _this = this;
        var request = Observable.fromPromise(this.authService.acquireTokenInBackground())
            .catch(function (error) { return _this.tokenRequestFailed(error); })
            .flatMap(function (token) {
            return makeRequest()
                .catch(function (response) { return _this.apiCallFailed(response); });
        });
        return request;
    };
    ;
    SecureHttp.prototype.tokenRequestFailed = function (error) {
        this.authService.showLoginPrompt();
        throw error;
    };
    SecureHttp.prototype.apiCallFailed = function (response) {
        if (response.status === 401) {
            this.authService.showLoginPrompt();
        }
        throw response;
    };
    SecureHttp.decorators = [
        { type: Injectable },
    ];
    /** @nocollapse */
    SecureHttp.ctorParameters = function () { return [
        { type: AuthHttp, },
        { type: AuthService, },
    ]; };
    return SecureHttp;
}());
export { SecureHttp };
//# sourceMappingURL=secure-http.service.js.map