"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
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);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseOAuthService = exports.OAuthClientWrapper = void 0;
var aurelia_fetch_client_1 = require("aurelia-fetch-client");
var aurelia_framework_1 = require("aurelia-framework");
var aurelia_router_1 = require("aurelia-router");
var data_context_1 = require("../data/data-context");
var config_1 = require("../config");
var ui_internal_1 = require("../utils/ui-internal");
var auth_service_1 = require("./auth-service");
var OAuthClientWrapper = (function () {
    function OAuthClientWrapper(config) {
        this.config = config;
    }
    OAuthClientWrapper.prototype.login = function () {
        if (sessionStorage.getItem('location') == null) {
            var url = location.pathname;
            if (false == url.startsWith('/login/')) {
                sessionStorage.setItem('location', JSON.stringify({ url: url }));
            }
        }
        this.loginWithRedirect();
    };
    return OAuthClientWrapper;
}());
exports.OAuthClientWrapper = OAuthClientWrapper;
var sleep = function (waitTime) { return __awaiter(void 0, void 0, void 0, function () { return __generator(this, function (_a) {
    return [2, new Promise(function (resolve) { return setTimeout(resolve, waitTime); })];
}); }); };
var BaseOAuthService = exports.BaseOAuthService = (function (_super) {
    __extends(BaseOAuthService, _super);
    function BaseOAuthService(router, app, dataContext, config, httpClient) {
        var _this = _super.call(this, config) || this;
        _this.router = router;
        _this.app = app;
        _this.dataContext = dataContext;
        _this.httpClient = httpClient;
        return _this;
    }
    BaseOAuthService.prototype.addBearerTokenToHttpClient = function () {
        var _this = this;
        var requestFn = function (message) { return __awaiter(_this, void 0, void 0, function () {
            var maxSleepTime, sleepInterval, totalSleepTime, _a, _b, _c, _d, _e, error_1;
            return __generator(this, function (_f) {
                switch (_f.label) {
                    case 0:
                        _f.trys.push([0, 7, , 8]);
                        if (!this.requestRequiresAuth(message)) return [3, 6];
                        maxSleepTime = 1000;
                        sleepInterval = 100;
                        totalSleepTime = 0;
                        _f.label = 1;
                    case 1:
                        _a = false;
                        return [4, this.isAuthenticated()];
                    case 2:
                        if (!(_a == (_f.sent()))) return [3, 4];
                        if (totalSleepTime >= maxSleepTime) {
                            console.error("After waiting ".concat(maxSleepTime, "ms user is still not authenticated, sending request without bearer token."));
                            return [2, message];
                        }
                        return [4, sleep(sleepInterval)];
                    case 3:
                        _f.sent();
                        totalSleepTime += sleepInterval;
                        return [3, 1];
                    case 4:
                        if (totalSleepTime > 0) {
                            console.warn("HTTP request slept for ".concat(totalSleepTime, "ms before isAuthenticated flag was true."));
                        }
                        _c = (_b = message.headers).append;
                        _d = ['Authorization'];
                        _e = "Bearer ".concat;
                        return [4, this.accessToken()];
                    case 5:
                        _c.apply(_b, _d.concat([_e.apply("Bearer ", [_f.sent()])]));
                        return [2, message];
                    case 6: return [2, message];
                    case 7:
                        error_1 = _f.sent();
                        console.log(error_1);
                        return [3, 8];
                    case 8: return [2];
                }
            });
        }); };
        this.httpClient.configure(function (config) {
            config
                .withInterceptor({
                request: requestFn
            });
        });
    };
    BaseOAuthService.prototype.accessToken = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.getClient()];
                    case 1: return [4, (_a.sent()).accessToken()];
                    case 2: return [2, _a.sent()];
                }
            });
        });
    };
    BaseOAuthService.prototype.getClient = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        if (!!this.client) return [3, 2];
                        _a = this;
                        return [4, this.makeClient()];
                    case 1:
                        _a.client = _b.sent();
                        _b.label = 2;
                    case 2: return [2, this.client];
                }
            });
        });
    };
    BaseOAuthService.prototype.login = function (navInstruction) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        sessionStorage.setItem('location', JSON.stringify({ url: navInstruction }));
                        return [4, this.getClient()];
                    case 1:
                        (_a.sent()).login();
                        return [2];
                }
            });
        });
    };
    BaseOAuthService.prototype.navigateToSavedInstruction = function () {
        var savedLocation = JSON.parse(sessionStorage.getItem('location'));
        var navigateTarget = (savedLocation === null || savedLocation === void 0 ? void 0 : savedLocation.url) || 'watchlist';
        sessionStorage.removeItem('location');
        this.router.navigate(navigateTarget);
    };
    BaseOAuthService.prototype.handleAuthentication = function () {
        return __awaiter(this, void 0, void 0, function () {
            var err_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 3, , 4]);
                        return [4, this.getClient()];
                    case 1: return [4, (_a.sent()).handleSignInRedirect()];
                    case 2:
                        _a.sent();
                        ui_internal_1.UIInternal.broadcast(ui_internal_1.UIInternal.EVT_AUTH_CHANGE, { authenticated: true });
                        return [3, 4];
                    case 3:
                        err_1 = _a.sent();
                        if (err_1.error_description == 'user is blocked') {
                            alert("Ce compte utilisateur est désactivé");
                        }
                        else {
                            alert("Ce compte utilisateur n'a pas été validé. Veuillez cliquez sur le lien que vous avec reçu dans l'email de bienvenue que vous avez reçu");
                        }
                        throw err_1;
                    case 4: return [2];
                }
            });
        });
    };
    BaseOAuthService.prototype.isAuthenticated = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.getClient()];
                    case 1: return [4, (_a.sent()).isAuthenticated()];
                    case 2: return [2, _a.sent()];
                }
            });
        });
    };
    BaseOAuthService.prototype.logout = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.getClient()];
                    case 1: return [4, (_a.sent()).logout()];
                    case 2:
                        _a.sent();
                        return [2];
                }
            });
        });
    };
    BaseOAuthService.prototype.getProfile = function () {
        var _a;
        return __awaiter(this, void 0, void 0, function () {
            var _b, _c;
            return __generator(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        _b = this;
                        return [4, this.dataContext.getCurrentUserProfile()];
                    case 1:
                        _b.currentUser = _d.sent();
                        if (!(this.currentUser == null)) return [3, 3];
                        return [4, this.logout()];
                    case 2:
                        _d.sent();
                        return [3, 6];
                    case 3:
                        _c = this;
                        return [4, this.getClient()];
                    case 4: return [4, (_d.sent()).getUserProfile()];
                    case 5:
                        _c.authProfile = _d.sent();
                        this.currentUser.avatarUri = (_a = this.authProfile) === null || _a === void 0 ? void 0 : _a.picture;
                        _d.label = 6;
                    case 6: return [2];
                }
            });
        });
    };
    BaseOAuthService.prototype.checkAccess = function (resource, action) {
        var _a;
        if (resource == null || action == null)
            return true;
        if (this.currentUser == null)
            return false;
        var scope = "".concat(action, ":").concat(resource.toLocaleLowerCase());
        return ((_a = this.currentUser.permissions) === null || _a === void 0 ? void 0 : _a.indexOf(scope)) >= 0;
    };
    BaseOAuthService = __decorate([
        (0, aurelia_framework_1.inject)(aurelia_router_1.Router, aurelia_framework_1.Aurelia, data_context_1.Datacontext, config_1.Config, aurelia_fetch_client_1.HttpClient),
        __metadata("design:paramtypes", [aurelia_router_1.Router, aurelia_framework_1.Aurelia, data_context_1.Datacontext,
            config_1.Config, aurelia_fetch_client_1.HttpClient])
    ], BaseOAuthService);
    return BaseOAuthService;
}(auth_service_1.AuthService));

//# sourceMappingURL=oauth-service.js.map
