"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.WebSocketServer = void 0;
var WebSocket = require("ws");
var WebSocketServerClient_1 = require("./WebSocketServerClient");
var DatabaseConnection_1 = require("./DatabaseConnection");
var Crypt_1 = require("./Crypt");
var Message_1 = require("./Messages/Message");
var Config_1 = require("./Config");
var openflow_api_1 = require("@openiap/openflow-api");
var client = require("prom-client");
var WebSocketServer = /** @class */ (function () {
    function WebSocketServer() {
    }
    WebSocketServer.update_message_queue_count = function (cli) {
        if (!Config_1.Config.prometheus_measure_queued_messages)
            return;
        var result = {};
        var keys = Object.keys(cli.messageQueue);
        keys.forEach(function (key) {
            try {
                var qmsg = cli.messageQueue[key];
                var o = qmsg.message;
                if (typeof o === "string")
                    o = JSON.parse(o);
                var msg = o;
                if (result[msg.command] == null)
                    result[msg.command] = 0;
                result[msg.command]++;
            }
            catch (error) {
                WebSocketServer._logger.error(error);
            }
        });
        var keys2 = Object.keys(result);
        WebSocketServer.message_queue_count.reset();
        WebSocketServer.message_queue_count.labels(cli.id).set(keys.length);
        keys2.forEach(function (key) {
            WebSocketServer.message_queue_count.labels(cli.id, key).set(result[key]);
        });
    };
    WebSocketServer.configure = function (logger, server, register) {
        var _this = this;
        this._clients = [];
        this._logger = logger;
        this._server = server;
        this._socketserver = new WebSocket.Server({ server: server });
        this._socketserver.on("connection", function (socketObject, req) {
            _this._clients.push(new WebSocketServerClient_1.WebSocketServerClient(logger, socketObject, req));
        });
        this._socketserver.on("error", function (error) {
            _this._logger.error(error);
        });
        if (!openflow_api_1.NoderedUtil.IsNullUndefinded(register))
            register.registerMetric(WebSocketServer.p_all);
        if (!openflow_api_1.NoderedUtil.IsNullUndefinded(register))
            register.registerMetric(WebSocketServer.websocket_incomming_stats);
        if (!openflow_api_1.NoderedUtil.IsNullUndefinded(register))
            register.registerMetric(WebSocketServer.websocket_queue_count);
        if (!openflow_api_1.NoderedUtil.IsNullUndefinded(register))
            register.registerMetric(WebSocketServer.websocket_queue_message_count);
        if (!openflow_api_1.NoderedUtil.IsNullUndefinded(register))
            register.registerMetric(WebSocketServer.websocket_rate_limit);
        if (!openflow_api_1.NoderedUtil.IsNullUndefinded(register))
            register.registerMetric(WebSocketServer.websocket_messages);
        if (!openflow_api_1.NoderedUtil.IsNullUndefinded(register))
            register.registerMetric(WebSocketServer.message_queue_count);
        if (!openflow_api_1.NoderedUtil.IsNullUndefinded(register))
            register.registerMetric(DatabaseConnection_1.DatabaseConnection.mongodb_query);
        if (!openflow_api_1.NoderedUtil.IsNullUndefinded(register))
            register.registerMetric(DatabaseConnection_1.DatabaseConnection.mongodb_query_count);
        if (!openflow_api_1.NoderedUtil.IsNullUndefinded(register))
            register.registerMetric(DatabaseConnection_1.DatabaseConnection.mongodb_aggregate);
        if (!openflow_api_1.NoderedUtil.IsNullUndefinded(register))
            register.registerMetric(DatabaseConnection_1.DatabaseConnection.mongodb_aggregate_count);
        setInterval(this.pingClients, 10000);
    };
    WebSocketServer.pingClients = function () {
        return __awaiter(this, void 0, void 0, function () {
            var count, i, cli, payload, clockTimestamp, tuser, l, m, error_1, now, seconds, i, cli;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        count = WebSocketServer._clients.length;
                        WebSocketServer.p_all.reset();
                        WebSocketServer.p_all.set(count);
                        i = WebSocketServer._clients.length - 1;
                        _a.label = 1;
                    case 1:
                        if (!(i >= 0)) return [3 /*break*/, 8];
                        cli = WebSocketServer._clients[i];
                        _a.label = 2;
                    case 2:
                        _a.trys.push([2, 5, , 6]);
                        if (!!openflow_api_1.NoderedUtil.IsNullEmpty(cli.jwt)) return [3 /*break*/, 4];
                        payload = Crypt_1.Crypt.decryptToken(cli.jwt);
                        clockTimestamp = Math.floor(Date.now() / 1000);
                        if (!((payload.exp - clockTimestamp) < 60)) return [3 /*break*/, 4];
                        WebSocketServer._logger.debug("Token for " + cli.id + "/" + cli.user.name + "/" + cli.clientagent + " expires in less than 1 minute, send new jwt to client");
                        return [4 /*yield*/, Message_1.Message.DoSignin(cli, null)];
                    case 3:
                        tuser = _a.sent();
                        if (tuser != null) {
                            l = new openflow_api_1.SigninMessage();
                            cli.jwt = Crypt_1.Crypt.createToken(tuser, Config_1.Config.shorttoken_expires_in);
                            l.jwt = cli.jwt;
                            l.user = tuser;
                            m = new Message_1.Message();
                            m.command = "refreshtoken";
                            m.data = JSON.stringify(l);
                            cli.Send(m);
                        }
                        else {
                            cli.Close();
                        }
                        _a.label = 4;
                    case 4: return [3 /*break*/, 6];
                    case 5:
                        error_1 = _a.sent();
                        console.error(error_1);
                        cli.Close();
                        return [3 /*break*/, 6];
                    case 6:
                        now = new Date();
                        seconds = (now.getTime() - cli.lastheartbeat.getTime()) / 1000;
                        if (seconds >= Config_1.Config.client_heartbeat_timeout) {
                            if (cli.user != null) {
                                WebSocketServer._logger.info("client " + cli.id + "/" + cli.user.name + "/" + cli.clientagent + " timeout, close down");
                            }
                            else {
                                WebSocketServer._logger.info("client not signed/" + cli.id + "/" + cli.clientagent + " timeout, close down");
                            }
                            cli.Close();
                        }
                        cli.ping();
                        if (!cli.connected() && cli.queuecount() == 0 && cli.streamcount() == 0) {
                            if (cli.user != null) {
                                WebSocketServer._logger.info("removing disconnected client " + cli.id + "/" + cli.user.name + "/" + cli.clientagent);
                            }
                            else {
                                WebSocketServer._logger.info("removing disconnected client " + cli.id + "/" + cli.clientagent + " timeout, close down");
                            }
                            WebSocketServer._clients.splice(i, 1);
                        }
                        _a.label = 7;
                    case 7:
                        i--;
                        return [3 /*break*/, 1];
                    case 8:
                        if (count !== WebSocketServer._clients.length) {
                            WebSocketServer._logger.info("new client count: " + WebSocketServer._clients.length);
                        }
                        // let openrpa: number = 0;
                        // this.p_online_clients.labels("openrpa").set(count);
                        for (i = 0; i < WebSocketServer._clients.length; i++) {
                            try {
                                cli = WebSocketServer._clients[i];
                                if (cli.user != null) {
                                    if (!openflow_api_1.NoderedUtil.IsNullEmpty(cli.clientagent)) {
                                        WebSocketServer.p_all.labels(cli.clientagent, cli.clientversion).inc();
                                    }
                                    // Lets assume only robots register queues ( not true )
                                    if (cli.clientagent == "openrpa") {
                                        Config_1.Config.db.db.collection("users").updateOne({ _id: cli.user._id }, { $set: { _rpaheartbeat: new Date(new Date().toISOString()), _heartbeat: new Date(new Date().toISOString()) } }).catch(function (err) {
                                            console.error(err);
                                        });
                                    }
                                    if (cli.clientagent == "nodered") {
                                        Config_1.Config.db.db.collection("users").updateOne({ _id: cli.user._id }, { $set: { _noderedheartbeat: new Date(new Date().toISOString()), _heartbeat: new Date(new Date().toISOString()) } }).catch(function (err) {
                                            console.error(err);
                                        });
                                    }
                                    if (cli.clientagent == "webapp" || cli.clientagent == "aiotwebapp") {
                                        Config_1.Config.db.db.collection("users").updateOne({ _id: cli.user._id }, { $set: { _webheartbeat: new Date(new Date().toISOString()), _heartbeat: new Date(new Date().toISOString()) } }).catch(function (err) {
                                            console.error(err);
                                        });
                                    }
                                    if (cli.clientagent == "powershell") {
                                        Config_1.Config.db.db.collection("users").updateOne({ _id: cli.user._id }, { $set: { _powershellheartbeat: new Date(new Date().toISOString()), _heartbeat: new Date(new Date().toISOString()) } }).catch(function (err) {
                                            console.error(err);
                                        });
                                    }
                                    if (cli.clientagent == "mobileapp" || cli.clientagent == "aiotmobileapp") {
                                        Config_1.Config.db.db.collection("users").updateOne({ _id: cli.user._id }, { $set: { _webheartbeat: new Date(new Date().toISOString()), _mobilheartbeat: new Date(new Date().toISOString()), _heartbeat: new Date(new Date().toISOString()) } }).catch(function (err) {
                                            console.error(err);
                                        });
                                    }
                                    else {
                                        // Should proberly turn this a little down, so we dont update all online users every 10th second
                                        Config_1.Config.db.db.collection("users").updateOne({ _id: cli.user._id }, { $set: { _heartbeat: new Date(new Date().toISOString()) } }).catch(function (err) {
                                            console.error(err);
                                        });
                                    }
                                }
                            }
                            catch (error) {
                                console.error(error);
                            }
                        }
                        return [2 /*return*/];
                }
            });
        });
    };
    WebSocketServer.p_all = new client.Gauge({
        name: 'openflow_websocket_online_clients',
        help: 'Total number of online websocket clients',
        labelNames: ["agent", "version"]
    });
    WebSocketServer.websocket_incomming_stats = new client.Counter({
        name: 'openflow_websocket_incomming_packages',
        help: 'Total number of websocket packages',
        labelNames: ["command"]
    });
    WebSocketServer.websocket_queue_count = new client.Gauge({
        name: 'openflow_websocket_queue_count',
        help: 'Total number of registered queues',
        labelNames: ["clientid"]
    });
    WebSocketServer.websocket_queue_message_count = new client.Counter({
        name: 'openflow_websocket_queue_message_count',
        help: 'Total number of queues messages',
        labelNames: ["queuename"]
    });
    WebSocketServer.websocket_rate_limit = new client.Counter({
        name: 'openflow_websocket_rate_limit_count',
        help: 'Total number of rate limited messages',
        labelNames: ["command"]
    });
    WebSocketServer.websocket_messages = new client.Histogram({
        name: 'openflow_websocket_messages_duration_seconds',
        help: 'Duration for handling websocket requests in microseconds',
        labelNames: ['command'],
        buckets: [0.1, 0.3, 0.5, 0.7, 1, 3, 5, 7, 10]
    });
    WebSocketServer.message_queue_count = new client.Gauge({
        name: 'openflow_message_queue_count',
        help: 'Total number messages waiting on reply from client',
        labelNames: ["clientid"]
    });
    return WebSocketServer;
}());
exports.WebSocketServer = WebSocketServer;
//# sourceMappingURL=WebSocketServer.js.map