"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 (_) 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.QueuedMessage = exports.WebSocketClientService = void 0;
var openflow_api_1 = require("@openiap/openflow-api");
var WebSocketClientService = /** @class */ (function () {
    function WebSocketClientService($rootScope, $location, $window) {
        this.$rootScope = $rootScope;
        this.$location = $location;
        this.$window = $window;
        this.logger = {
            info: function (msg) { console.log(msg); },
            verbose: function (msg) { console.debug(msg); },
            error: function (msg) { console.error(msg); },
            debug: function (msg) { console.debug(msg); },
            silly: function (msg) { console.debug(msg); }
        };
        this.user = null;
        this.jwt = null;
        this.version = "";
        this.messageQueue = {};
        this.usingCordova = false;
        this.connected = false;
        this.domain = "";
        this.allow_user_registration = false;
        this.allow_personal_nodered = false;
        this.auto_create_personal_nodered_group = false;
        this.namespace = "";
        this.nodered_domain_schema = "";
        this.websocket_package_size = 4096;
        this.stripe_api_key = "";
        this.validate_user_form = "";
        console.debug("WebSocketClientService::constructor");
        this.load();
    }
    WebSocketClientService.prototype.load = function () {
        var _this = this;
        this.getJSON("/config", function (error, data) { return __awaiter(_this, void 0, void 0, function () {
            var wsurl_1, cli;
            var _this = this;
            return __generator(this, function (_a) {
                if (openflow_api_1.NoderedUtil.IsNullUndefinded(data)) {
                    console.error("/config return null");
                    return [2 /*return*/];
                }
                try {
                    wsurl_1 = data.wsurl;
                    this.version = data.version;
                    this.domain = data.domain;
                    this.version = data.version;
                    this.allow_user_registration = data.allow_user_registration;
                    this.allow_personal_nodered = data.allow_personal_nodered;
                    this.auto_create_personal_nodered_group = data.auto_create_personal_nodered_group;
                    this.namespace = data.namespace;
                    this.nodered_domain_schema = data.nodered_domain_schema;
                    this.websocket_package_size = data.websocket_package_size;
                    this.stripe_api_key = data.stripe_api_key;
                    this.validate_user_form = data.validate_user_form;
                    if (openflow_api_1.WebSocketClient.instance == null) {
                        cli = new openflow_api_1.WebSocketClient(this.logger, wsurl_1);
                        cli.agent = "webapp";
                        cli.version = data.version;
                        cli.events.on('connect', function () {
                            _this.logger.info('connected to ' + wsurl_1);
                            _this.loadToken();
                        });
                        cli.connect();
                    }
                }
                catch (error) {
                    console.error(error);
                }
                return [2 /*return*/];
            });
        }); });
    };
    WebSocketClientService.prototype.loadToken = function () {
        var _this = this;
        openflow_api_1.WebSocketClient.instance.getJSON("/jwt", function (error, data) { return __awaiter(_this, void 0, void 0, function () {
            var _url, result, redirecturl, error_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (data !== null && data !== undefined) {
                            if (data.jwt === null || data.jwt === undefined || data.jwt.trim() === "") {
                                data.jwt = null;
                            }
                            if (data.rawAssertion === null || data.rawAssertion === undefined || data.rawAssertion.trim() === "") {
                                data.rawAssertion = null;
                            }
                            if (data.jwt === null && data.rawAssertion === null) {
                                console.debug("data.jwt and data.rawAssertion is null");
                                data = null;
                            }
                        }
                        _url = this.$location.absUrl();
                        if (data === null || data === undefined) {
                            if (this.$location.path() !== "/Login" && this.$location.path() !== "/Signup") {
                                // const _url = this.$location.absUrl();
                                // this.setCookie("weburl", _url, 365);
                                this.setCookie("weburl", this.$location.path(), 365);
                                this.$location.path("/Login");
                                this.$rootScope.$apply();
                            }
                            return [2 /*return*/];
                        }
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, openflow_api_1.NoderedUtil.SigninWithToken(data.jwt, data.rawAssertion, null)];
                    case 2:
                        result = _a.sent();
                        this.user = result.user;
                        this.jwt = result.jwt;
                        this.$rootScope.$broadcast("signin", result.user);
                        redirecturl = this.getCookie("weburl");
                        if (!openflow_api_1.NoderedUtil.IsNullEmpty(redirecturl)) {
                            this.deleteCookie("weburl");
                            this.$location.path(redirecturl);
                        }
                        return [3 /*break*/, 4];
                    case 3:
                        error_1 = _a.sent();
                        if (error_1 == "User not validated, please login again") {
                            this.setCookie("validateurl", this.$location.path(), 365);
                            setTimeout(function () {
                                top.location.href = '/login';
                                document.write('<script>top.location = "/login";</script>');
                            }, 500);
                        }
                        console.error(error_1);
                        try {
                            document.write(error_1);
                            document.write("<br/><a href=\"/Signout\">Signout</a>");
                        }
                        catch (error) {
                        }
                        return [3 /*break*/, 4];
                    case 4: return [2 /*return*/];
                }
            });
        }); });
    };
    WebSocketClientService.prototype.impersonate = function (userid) {
        return __awaiter(this, void 0, void 0, function () {
            var result, error_2;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        return [4 /*yield*/, openflow_api_1.NoderedUtil.SigninWithToken(this.jwt, null, userid)];
                    case 1:
                        result = _a.sent();
                        this.user = result.user;
                        this.jwt = result.jwt;
                        this.$rootScope.$broadcast("signin", result.user);
                        return [3 /*break*/, 3];
                    case 2:
                        error_2 = _a.sent();
                        console.error(error_2);
                        return [3 /*break*/, 3];
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    WebSocketClientService.prototype.setCookie = function (cname, cvalue, exdays) {
        var d = new Date();
        d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
        var expires = "expires=" + d.toUTCString();
        document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
    };
    WebSocketClientService.prototype.getCookie = function (cname) {
        var name = cname + "=";
        var decodedCookie = decodeURIComponent(document.cookie);
        var ca = decodedCookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') {
                c = c.substring(1);
            }
            if (c.indexOf(name) == 0) {
                return c.substring(name.length, c.length);
            }
        }
        return "";
    };
    WebSocketClientService.prototype.deleteCookie = function (cname) {
        document.cookie = cname + "=;Thu, 01 Jan 1970 00:00:00 UTC;path=/";
    };
    WebSocketClientService.prototype.getJSON = function (url, callback) {
        var xhr = new XMLHttpRequest();
        xhr.open("GET", url, true);
        xhr.responseType = "json";
        xhr.onload = function () {
            var status = xhr.status;
            if (status === 200) {
                callback(null, xhr.response);
            }
            else {
                callback(status, xhr.response);
            }
        };
        xhr.send();
    };
    WebSocketClientService.prototype.onSignedin = function (callback) {
        var _this = this;
        if (this.user !== null) {
            callback(this.user);
            return;
        }
        var cleanup = this.$rootScope.$on('signin', function (event, data) {
            if (event && data) { }
            cleanup();
            callback(_this.user);
        });
    };
    WebSocketClientService.prototype.onConnected = function (callback) {
        if (this.connected) {
            callback();
            return;
        }
        var cleanup = this.$rootScope.$on('socketopen', function (event, data) {
            if (event && data) { }
            cleanup();
            callback();
        });
    };
    WebSocketClientService.$inject = ["$rootScope", "$location", "$window"];
    return WebSocketClientService;
}());
exports.WebSocketClientService = WebSocketClientService;
var QueuedMessage = /** @class */ (function () {
    function QueuedMessage(message, cb, status) {
        this.id = message.id;
        this.message = message;
        this.cb = cb;
        this.status = status;
    }
    return QueuedMessage;
}());
exports.QueuedMessage = QueuedMessage;
//# sourceMappingURL=WebSocketClientService.js.map