"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.nodered_image = exports.QueuedMessage = exports.WebSocketClientService = void 0;
const openflow_api_1 = require("@openiap/openflow-api");
class WebSocketClientService {
    constructor($rootScope, $location, $window) {
        this.$rootScope = $rootScope;
        this.$location = $location;
        this.$window = $window;
        this.logger = {
            info(msg) { console.log(msg); },
            verbose(msg) { console.debug(msg); },
            error(msg) { console.error(msg); },
            debug(msg) { console.debug(msg); },
            silly(msg) { console.debug(msg); }
        };
        this.customer = null;
        // public user: TokenUser = null;
        // public jwt: string = null;
        this.version = "";
        this.wsurl = "";
        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 = "";
        this.validate_emails = false;
        this.forgot_pass_emails = false;
        this.forceddomains = [];
        this.collections_with_text_index = [];
        this.timeseries_collections = [];
        this.ping_clients_interval = 10000;
        this.validlicense = false;
        this.load();
    }
    load() {
        this.getJSON("/config", async (error, data) => {
            if (openflow_api_1.NoderedUtil.IsNullUndefinded(data)) {
                return;
            }
            try {
                const wsurl = data.wsurl;
                this.wsurl = 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;
                this.validate_emails = data.validate_emails;
                this.forgot_pass_emails = data.forgot_pass_emails;
                this.multi_tenant = data.multi_tenant;
                this.nodered_images = data.nodered_images;
                this.enable_entity_restriction = data.enable_entity_restriction;
                this.enable_web_tours = data.enable_web_tours;
                this.enable_nodered_tours = data.enable_nodered_tours;
                this.forceddomains = data.forceddomains;
                if (data.collections_with_text_index)
                    this.collections_with_text_index = data.collections_with_text_index;
                if (data.timeseries_collections)
                    this.timeseries_collections = data.timeseries_collections;
                this.ping_clients_interval = data.ping_clients_interval;
                this.validlicense = data.validlicense;
                if (openflow_api_1.NoderedUtil.IsNullUndefinded(openflow_api_1.WebSocketClient.instance)) {
                    const cli = new openflow_api_1.WebSocketClient(this.logger, wsurl);
                    cli.agent = "webapp";
                    cli.version = data.version;
                    cli.events.on('connect', () => {
                        this.logger.info('connected to ' + wsurl);
                        this.loadToken();
                    });
                    cli.events.on('refreshtoken', (user) => {
                        this.$rootScope.$broadcast("refreshtoken", user);
                    });
                    cli.connect();
                }
            }
            catch (error) {
                console.error(error);
            }
        });
    }
    loadToken() {
        openflow_api_1.WebSocketClient.instance.getJSON("/jwt", async (error, data) => {
            if (!openflow_api_1.NoderedUtil.IsNullUndefinded(data)) {
                if (openflow_api_1.NoderedUtil.IsNullUndefinded(data.jwt) || data.jwt.trim() === "") {
                    data.jwt = null;
                }
                if (openflow_api_1.NoderedUtil.IsNullUndefinded(data.rawAssertion) || data.rawAssertion.trim() === "") {
                    data.rawAssertion = null;
                }
                if (openflow_api_1.NoderedUtil.IsNullUndefinded(data.jwt)) {
                    data = null;
                }
            }
            const _url = this.$location.absUrl();
            if (openflow_api_1.NoderedUtil.IsNullUndefinded(data)) {
                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;
            }
            try {
                const result = await openflow_api_1.NoderedUtil.SigninWithToken({ jwt: data.jwt, rawAssertion: data.rawAssertion });
                this.customer = null;
                if (!openflow_api_1.NoderedUtil.IsNullEmpty(openflow_api_1.WebSocketClient.instance.user.selectedcustomerid)) {
                    const customers = await openflow_api_1.NoderedUtil.Query({ collectionname: "users", query: { _type: "customer", "$or": [{ "_id": openflow_api_1.WebSocketClient.instance.user.selectedcustomerid }, { "_id": openflow_api_1.WebSocketClient.instance.user.customerid }] } });
                    if (customers && customers.length > 0 && (openflow_api_1.WebSocketClient.instance.user.selectedcustomerid != null)) {
                        if (openflow_api_1.WebSocketClient.instance.user.selectedcustomerid != null) {
                            for (let cust of customers)
                                if (cust._id == openflow_api_1.WebSocketClient.instance.user.selectedcustomerid)
                                    this.customer = cust;
                        }
                    }
                }
                this.$rootScope.$broadcast("signin", result.user);
                const redirecturl = this.getCookie("weburl");
                if (!openflow_api_1.NoderedUtil.IsNullEmpty(redirecturl)) {
                    this.deleteCookie("weburl");
                    this.$location.path(redirecturl);
                }
            }
            catch (error) {
                if (error == "User not validated, please login again") {
                    this.setCookie("validateurl", this.$location.path(), 365);
                    setTimeout(() => {
                        top.location.href = '/login';
                        document.write('<script>top.location = "/login";</script>');
                    }, 500);
                }
                console.error(error);
                try {
                    document.write(error);
                    document.write("<br/><a href=\"/Signout\">Signout</a>");
                }
                catch (error) {
                }
            }
        });
    }
    async impersonate(userid) {
        try {
            const result = await openflow_api_1.NoderedUtil.SigninWithToken({ jwt: openflow_api_1.WebSocketClient.instance.jwt, impersonate: userid });
            this.$rootScope.$broadcast("signin", result.user);
        }
        catch (error) {
            console.error(error);
        }
    }
    setCookie(cname, cvalue, exdays) {
        const d = new Date();
        d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
        const expires = "expires=" + d.toUTCString();
        document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
    }
    getCookie(cname) {
        const name = cname + "=";
        const decodedCookie = decodeURIComponent(document.cookie);
        const ca = decodedCookie.split(';');
        for (let i = 0; i < ca.length; i++) {
            let c = ca[i];
            while (c.charAt(0) == ' ') {
                c = c.substring(1);
            }
            if (c.indexOf(name) == 0) {
                return c.substring(name.length, c.length);
            }
        }
        return "";
    }
    deleteCookie(cname) {
        document.cookie = cname + "=;Thu, 01 Jan 1970 00:00:00 UTC;path=/";
    }
    getJSON(url, callback) {
        const xhr = new XMLHttpRequest();
        xhr.open("GET", url, true);
        xhr.responseType = "json";
        xhr.onload = function () {
            const status = xhr.status;
            if (status === 200) {
                callback(null, xhr.response);
            }
            else {
                callback(status, xhr.response);
            }
        };
        xhr.send();
    }
    onSignedin(callback) {
        if (!openflow_api_1.NoderedUtil.IsNullUndefinded(openflow_api_1.WebSocketClient.instance) && !openflow_api_1.NoderedUtil.IsNullUndefinded(openflow_api_1.WebSocketClient.instance.user)) {
            callback(openflow_api_1.WebSocketClient.instance.user);
            return;
        }
        const cleanup = this.$rootScope.$on('signin', (event, data) => {
            if (event && data) { }
            cleanup();
            callback(openflow_api_1.WebSocketClient.instance.user);
        });
    }
    onConnected(callback) {
        if (this.connected) {
            callback();
            return;
        }
        const cleanup = this.$rootScope.$on('socketopen', (event, data) => {
            if (event && data) { }
            cleanup();
            callback();
        });
    }
}
exports.WebSocketClientService = WebSocketClientService;
WebSocketClientService.$inject = ["$rootScope", "$location", "$window"];
class QueuedMessage {
    constructor(message, cb, status) {
        this.id = message.id;
        this.message = message;
        this.cb = cb;
        this.status = status;
    }
}
exports.QueuedMessage = QueuedMessage;
class nodered_image {
}
exports.nodered_image = nodered_image;
//# sourceMappingURL=WebSocketClientService.js.map