"use strict";
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 };
    }
};
var __values = (this && this.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var deepmerge_1 = __importDefault(require("deepmerge"));
var BringgDashboardSDK_1 = require("../../BringgDashboardSDK");
var BringgDashboardSDK_consts_1 = require("../../BringgDashboardSDK.consts");
var ConfigurationProvider_1 = require("../../Core/ConfigurationProvider");
var Enums_1 = require("../../Core/Http/Enums");
var URLEndpoint_1 = __importDefault(require("../../Core/Http/URLEndpoint"));
var Logger_1 = __importDefault(require("../../Core/Logger"));
var PersistentConnection_1 = __importDefault(require("../PersistentConnection"));
var PubSubEvents_1 = require("../PubSubEvents");
var AuthService_1 = __importDefault(require("./AuthService"));
var Session = /** @class */ (function () {
    function Session(user) {
        this.merchant = null;
        this.webApplicationConfiguration = null;
        this.user = user;
        this.eventHandlers = new Set();
        this.sendDataEvent = this.sendDataEvent.bind(this);
    }
    Session.prototype.setEventHandler = function (fun) {
        this.eventHandlers.add(fun);
    };
    Session.prototype.sendDataEvent = function (name, message) {
        Session.sendDataEventInternal(this.eventHandlers, name, message);
    };
    Session.prototype.update = function (key, value) {
        if (!this[key]) {
            throw new Error("tried to update key: ".concat(key, " not existing!"));
        }
        //when merging 2 arrays, prefer they new one as it full update
        var chooseLatest = function (target, source) { return source; };
        this[key] = (0, deepmerge_1.default)(this[key], value, { arrayMerge: chooseLatest });
    };
    Session.sendDataEventInternal = function (eventHandlers, name, message) {
        eventHandlers.forEach(function (fun) { return Session.checked(fun, name, message); });
    };
    Session._merge = function (obj1, obj2) {
        var e_1, _a;
        try {
            for (var obj2_1 = __values(obj2), obj2_1_1 = obj2_1.next(); !obj2_1_1.done; obj2_1_1 = obj2_1.next()) {
                var attrname = obj2_1_1.value;
                obj1[attrname] = obj2[attrname];
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (obj2_1_1 && !obj2_1_1.done && (_a = obj2_1.return)) _a.call(obj2_1);
            }
            finally { if (e_1) throw e_1.error; }
        }
    };
    Session.fromUser = function (user, initRealTime) {
        if (initRealTime === void 0) { initRealTime = true; }
        return __awaiter(this, void 0, void 0, function () {
            var ses, _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        ses = new Session(user);
                        if (!initRealTime) return [3 /*break*/, 2];
                        _a = ses;
                        return [4 /*yield*/, PersistentConnection_1.default.init(ses)];
                    case 1:
                        _a._persistentConnection = _b.sent();
                        ses._persistentConnection.subscribe(PubSubEvents_1.EMPLOYEE_UPDATE_EVENT, function (user) {
                            if (user.uuid === ses.user.uuid) {
                                Session._merge(ses.user, user);
                                ses.sendDataEvent('current user updated', ses.user);
                            }
                        });
                        _b.label = 2;
                    case 2: return [2 /*return*/, ses];
                }
            });
        });
    };
    Object.defineProperty(Session.prototype, "userId", {
        get: function () {
            return this.user.id;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Session.prototype, "region", {
        get: function () {
            return this.user.region ? this.user.region : (0, BringgDashboardSDK_1.getConfigurationProvider)().getDefaultRegion();
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Session.prototype, "clientId", {
        get: function () {
            return (0, BringgDashboardSDK_1.getConfigurationProvider)().getClientId();
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Session.prototype, "config", {
        get: function () {
            // eslint-disable-next-line @typescript-eslint/no-this-alias
            var _this = this;
            return new (/** @class */ (function () {
                function class_1() {
                }
                class_1.prototype.getApiEndpoint = function () {
                    return URLEndpoint_1.default.parse((0, BringgDashboardSDK_1.getConfigurationProvider)().getApiEndpoint(_this.region));
                };
                class_1.prototype.getAuthenticationEndpoint = function () {
                    return URLEndpoint_1.default.parse((0, BringgDashboardSDK_1.getConfigurationProvider)().getAuthenticationEndpoint(_this.region));
                };
                class_1.prototype.getMonitoringEndpoint = function () {
                    return URLEndpoint_1.default.parse((0, BringgDashboardSDK_1.getConfigurationProvider)().getMonitoringEndpoint(_this.region));
                };
                return class_1;
            }()))();
        },
        enumerable: false,
        configurable: true
    });
    Session.init = function (params) {
        return __awaiter(this, void 0, void 0, function () {
            var user, authService, response, _a, email, password, merchant_uuid, otp, recaptchaToken, recaptcha_qa_token, region, response, emailParams, response, sessionParams, response, codeExchangeParams, response;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        user = params.user;
                        if (user) {
                            return [2 /*return*/, Session.fromUser(user)];
                        }
                        authService = AuthService_1.default.init(params.region);
                        if (!params.authenticationToken) return [3 /*break*/, 2];
                        return [4 /*yield*/, authService.loginWithToken(params.authenticationToken)];
                    case 1:
                        response = _b.sent();
                        return [2 /*return*/, Session.fromUser(response)];
                    case 2:
                        if (!params.otp) return [3 /*break*/, 4];
                        _a = params, email = _a.email, password = _a.password, merchant_uuid = _a.merchant_uuid, otp = _a.otp, recaptchaToken = _a.recaptchaToken, recaptcha_qa_token = _a.recaptcha_qa_token, region = _a.region;
                        return [4 /*yield*/, authService.loginWithOTP(email, password, otp, merchant_uuid, recaptchaToken, recaptcha_qa_token, region)];
                    case 3:
                        response = _b.sent();
                        return [2 /*return*/, Session.fromUser(response)];
                    case 4:
                        if (!params.email) return [3 /*break*/, 6];
                        emailParams = params;
                        return [4 /*yield*/, this.loginWithEmailRetry(params.region, emailParams.email, emailParams.password, emailParams.merchant_uuid, emailParams.recaptchaToken, emailParams.recaptcha_qa_token, 0)];
                    case 5:
                        response = _b.sent();
                        return [2 /*return*/, Session.fromUser(response)];
                    case 6:
                        if (!params.code) return [3 /*break*/, 8];
                        sessionParams = params;
                        return [4 /*yield*/, authService.loginWithSessionCode(sessionParams.code, sessionParams.session)];
                    case 7:
                        response = _b.sent();
                        return [2 /*return*/, Session.fromUser(response)];
                    case 8:
                        codeExchangeParams = params;
                        if (!(codeExchangeParams.token && codeExchangeParams.secret)) return [3 /*break*/, 10];
                        return [4 /*yield*/, authService.loginWithOneTimeCode(codeExchangeParams.token, codeExchangeParams.secret)];
                    case 9:
                        response = _b.sent();
                        return [2 /*return*/, Session.fromUser(response)];
                    case 10: throw new Error('Unknown session initialization parameters type.');
                }
            });
        });
    };
    Session.loginWithEmailRetry = function (region, email, password, merchant_uuid, recaptchaToken, recaptcha_qa_token, loginRetryCount) {
        return __awaiter(this, void 0, void 0, function () {
            var currentRegion, authService, user, error_1;
            var _this_1 = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        currentRegion = region || (0, BringgDashboardSDK_1.getConfigurationProvider)().getDefaultRegion();
                        loginRetryCount++;
                        authService = AuthService_1.default.init(currentRegion);
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, authService.loginWithEmail(email, password, merchant_uuid, recaptchaToken, recaptcha_qa_token)];
                    case 2:
                        user = _a.sent();
                        return [2 /*return*/, user];
                    case 3:
                        error_1 = _a.sent();
                        if (loginRetryCount < 10 && error_1.message === Enums_1.REGION_NOT_WORKING) {
                            Logger_1.default.error("Region is not accessible - ".concat(currentRegion, ", ").concat(error_1.message));
                            return [2 /*return*/, new Promise(function (resolve, reject) {
                                    setTimeout(function () { return __awaiter(_this_1, void 0, void 0, function () {
                                        var _a, e_2;
                                        return __generator(this, function (_b) {
                                            switch (_b.label) {
                                                case 0:
                                                    _b.trys.push([0, 2, , 3]);
                                                    _a = resolve;
                                                    return [4 /*yield*/, this.loginWithEmailRetry(ConfigurationProvider_1.ConfigurationProvider.getNextRegion(currentRegion), email, password, merchant_uuid, recaptchaToken, recaptcha_qa_token, loginRetryCount)];
                                                case 1:
                                                    _a.apply(void 0, [_b.sent()]);
                                                    return [3 /*break*/, 3];
                                                case 2:
                                                    e_2 = _b.sent();
                                                    reject(e_2);
                                                    return [3 /*break*/, 3];
                                                case 3: return [2 /*return*/];
                                            }
                                        });
                                    }); }, 100);
                                })];
                        }
                        else {
                            throw error_1;
                        }
                        return [3 /*break*/, 4];
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * need this for the sake of explicit update in case realtime is down
     */
    Session.prototype.refreshCurrentUser = function () {
        return __awaiter(this, void 0, void 0, function () {
            var user;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, AuthService_1.default.init(this.user.region).loginWithToken(this.user.authentication_token)];
                    case 1:
                        user = _a.sent();
                        Session._merge(this.user, user);
                        this.sendDataEvent('current user updated', this.user);
                        return [2 /*return*/, this.user];
                }
            });
        });
    };
    Session.prototype.logout = function (keepServerSession) {
        if (keepServerSession === void 0) { keepServerSession = false; }
        return __awaiter(this, void 0, void 0, function () {
            var handlers;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        handlers = new Set(this.eventHandlers.values());
                        Session.sendDataEventInternal(handlers, BringgDashboardSDK_consts_1.GlobalEvents.SDK_DISPOSING);
                        this.eventHandlers.clear();
                        return [4 /*yield*/, this.persistentConnection.dispose()];
                    case 1:
                        _a.sent();
                        Session.sendDataEventInternal(handlers, BringgDashboardSDK_consts_1.GlobalEvents.SDK_DISPOSED);
                        if (!!keepServerSession) return [3 /*break*/, 3];
                        return [4 /*yield*/, AuthService_1.default.init(this.user.region).logout(this.user.authentication_token)];
                    case 2: return [2 /*return*/, _a.sent()];
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    Session.prototype.switchAccounts = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _a, _b;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        _b = (_a = Session).fromUser;
                        return [4 /*yield*/, AuthService_1.default.init(this.user.region).switchAccounts(this.user.authentication_token)];
                    case 1: return [2 /*return*/, _b.apply(_a, [_c.sent()])];
                }
            });
        });
    };
    Session.prototype.impersonate = function (user_id) {
        return __awaiter(this, void 0, void 0, function () {
            var newUser;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, AuthService_1.default.init(this.user.region).impersonate(this.user.authentication_token, user_id)];
                    case 1:
                        newUser = _a.sent();
                        newUser.original_user = this.user;
                        return [2 /*return*/, Session.fromUser(newUser)];
                }
            });
        });
    };
    Session.prototype.impersonateByTeam = function (team_id) {
        return __awaiter(this, void 0, void 0, function () {
            var newUser;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, AuthService_1.default.init(this.user.region).impersonateByTeam(this.user.authentication_token, team_id)];
                    case 1:
                        newUser = _a.sent();
                        newUser.original_user = this.user;
                        return [2 /*return*/, Session.fromUser(newUser)];
                }
            });
        });
    };
    Session.prototype.unwindImpersonation = function () {
        return __awaiter(this, void 0, void 0, function () {
            var newUser;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, AuthService_1.default.init(this.user.region).unwind(this.user.authentication_token)];
                    case 1:
                        newUser = _a.sent();
                        return [2 /*return*/, Session.fromUser(newUser)];
                }
            });
        });
    };
    Session.initWithAuthToken = function (region, authToken, initRealTime) {
        if (initRealTime === void 0) { initRealTime = true; }
        return __awaiter(this, void 0, void 0, function () {
            var authService, user;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        authService = AuthService_1.default.init(region);
                        return [4 /*yield*/, authService.loginWithToken(authToken)];
                    case 1:
                        user = _a.sent();
                        return [2 /*return*/, Session.fromUser(user, initRealTime)];
                }
            });
        });
    };
    Object.defineProperty(Session.prototype, "persistentConnection", {
        get: function () {
            return this._persistentConnection;
        },
        enumerable: false,
        configurable: true
    });
    Session.checked = function (fun, name, message) {
        try {
            fun(name, message);
        }
        catch (e) {
            // do nothing
        }
    };
    return Session;
}());
exports.default = Session;
//# sourceMappingURL=Session.js.map