var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Injectable } from '@angular/core';
import { from, Subject, throwError } from 'rxjs';
import { switchMap, catchError, take } from 'rxjs/operators';
import { AuthService } from '../auth';
var OAUTH2_TOKENS_URL = '/oauth2/tokens';
var RefreshTokenInterceptor = /** @class */ (function () {
    function RefreshTokenInterceptor(authService) {
        this.authService = authService;
        this.refreshTokenInProgress = false;
        this.refreshTokenSubject = new Subject();
    }
    RefreshTokenInterceptor.prototype.intercept = function (request, next) {
        var _this = this;
        return next.handle(request).pipe(catchError(function (error) {
            // Ignore refresh requests themselves
            if (request.url.includes(OAUTH2_TOKENS_URL)) {
                return throwError(error);
            }
            // Ignore non-401 errors
            if (error.status !== 401) {
                return throwError(error);
            }
            // Queue retries while token is being refreshed
            if (_this.refreshTokenInProgress) {
                return _this.refreshTokenSubject.pipe(take(1), switchMap(function (refreshSuccess) {
                    if (refreshSuccess) {
                        // Refire refreshed request
                        console.log('Retrying API call...');
                        return next.handle(_this.refreshRequest(request));
                    }
                    // Re-throw original error
                    return throwError(error);
                }));
            }
            console.log('Attempting OAuth2 tokens refresh...');
            _this.refreshTokenInProgress = true;
            return from(_this.authService.renewTokens()).pipe(switchMap(function () {
                _this.refreshTokenInProgress = false;
                _this.refreshTokenSubject.next(true);
                console.log('Retrying API call...');
                // Refire refreshed request
                return next.handle(_this.refreshRequest(request));
            }), catchError(function (err) {
                _this.refreshTokenInProgress = false;
                _this.refreshTokenSubject.next(false);
                console.error('Failed to refresh access token', err);
                return throwError(err);
            }));
        }));
    };
    RefreshTokenInterceptor.prototype.refreshRequest = function (request) {
        var accessToken = this.authService.getAccessToken();
        // Clone immutable request with new access token
        return request.clone({
            setHeaders: {
                'Authorization': "Bearer " + accessToken,
            }
        });
    };
    RefreshTokenInterceptor = __decorate([
        Injectable(),
        __metadata("design:paramtypes", [AuthService])
    ], RefreshTokenInterceptor);
    return RefreshTokenInterceptor;
}());
export { RefreshTokenInterceptor };
//# sourceMappingURL=refresh-token.interceptor.js.map