"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
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 Crypt_1 = require("./Crypt");
var Message_1 = require("./Messages/Message");
var Config_1 = require("./Config");
var openflow_api_1 = require("@openiap/openflow-api");
var Logger_1 = require("./Logger");
var WebSocketServer = /** @class */ (function () {
    function WebSocketServer() {
    }
    WebSocketServer.update_message_queue_count = function (cli) {
        if (!Config_1.Config.prometheus_measure_queued_messages)
            return;
        if (openflow_api_1.NoderedUtil.IsNullUndefinded(WebSocketServer.message_queue_count))
            return;
        // const result: any = {};
        var keys = Object.keys(cli.messageQueue);
        WebSocketServer.message_queue_count.bind(__assign(__assign({}, Logger_1.Logger.otel.defaultlabels), { clientid: cli.id })).update(keys.length);
    };
    WebSocketServer.update_mongodb_watch_count = function (cli) {
        if (!Config_1.Config.prometheus_measure__mongodb_watch)
            return;
        if (openflow_api_1.NoderedUtil.IsNullUndefinded(WebSocketServer.mongodb_watch_count))
            return;
        var result = {};
        var total = 0;
        WebSocketServer.mongodb_watch_count.clear();
        for (var i = WebSocketServer._clients.length - 1; i >= 0; i--) {
            var cli_1 = WebSocketServer._clients[i];
            WebSocketServer.mongodb_watch_count.bind(__assign(__assign({}, Logger_1.Logger.otel.defaultlabels), { clientid: cli_1.id, agent: cli_1.clientagent })).update(cli_1.streamcount());
        }
    };
    WebSocketServer.configure = function (server) {
        var _this = this;
        this._clients = [];
        this._server = server;
        this._socketserver = new WebSocket.Server({ server: server });
        this._socketserver.on("connection", function (socketObject, req) {
            _this._clients.push(new WebSocketServerClient_1.WebSocketServerClient(socketObject, req));
        });
        this._socketserver.on("error", function (error) {
            Logger_1.Logger.instanse.error(error);
        });
        if (!openflow_api_1.NoderedUtil.IsNullUndefinded(Logger_1.Logger.otel)) {
            WebSocketServer.p_all = Logger_1.Logger.otel.meter.createUpDownSumObserver("openflow_websocket_online_clients", {
                description: 'Total number of online websocket clients'
            }); // "agent", "version"
            WebSocketServer.websocket_queue_count = Logger_1.Logger.otel.meter.createUpDownSumObserver("openflow_websocket_queue", {
                description: 'Total number of registered queues'
            }); // "clientid"
            WebSocketServer.websocket_queue_message_count = Logger_1.Logger.otel.meter.createUpDownSumObserver("openflow_websocket_queue_message", {
                description: 'Total number of queues messages'
            }); // "queuename"
            WebSocketServer.websocket_rate_limit = Logger_1.Logger.otel.meter.createUpDownSumObserver("openflow_websocket_rate_limit", {
                description: 'Total number of rate limited messages'
            }); // "command"
            WebSocketServer.websocket_errors = Logger_1.Logger.otel.meter.createUpDownSumObserver("openflow_websocket_errors", {
                description: 'Total number of websocket errors'
            }); // 
            WebSocketServer.websocket_messages = Logger_1.Logger.otel.meter.createValueRecorder('openflow_websocket_messages_duration_seconds', {
                description: 'Duration for handling websocket requests',
                boundaries: Logger_1.Logger.otel.default_boundaries
            }); // "command"
            WebSocketServer.message_queue_count = Logger_1.Logger.otel.meter.createUpDownSumObserver("openflow_message_queue", {
                description: 'Total number messages waiting on reply from client'
            }); // "clientid"
            WebSocketServer.mongodb_watch_count = Logger_1.Logger.otel.meter.createUpDownSumObserver("mongodb_watch", {
                description: 'Total number af steams  watching for changes'
            }); // "agent", "clientid"
        }
        setInterval(this.pingClients, 10000);
    };
    WebSocketServer.pingClients = function () {
        return __awaiter(this, void 0, void 0, function () {
            var span, count, i, cli, payload, clockTimestamp, tuser, l, m, error_1, now, seconds, p_all_1, i, cli, keys, error_2;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        span = Logger_1.Logger.otel.startSpan("WebSocketServer.pingClients");
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 10, 11, 12]);
                        count = WebSocketServer._clients.length;
                        i = WebSocketServer._clients.length - 1;
                        _a.label = 2;
                    case 2:
                        if (!(i >= 0)) return [3 /*break*/, 9];
                        cli = WebSocketServer._clients[i];
                        _a.label = 3;
                    case 3:
                        _a.trys.push([3, 6, , 7]);
                        if (!!openflow_api_1.NoderedUtil.IsNullEmpty(cli.jwt)) return [3 /*break*/, 5];
                        payload = Crypt_1.Crypt.decryptToken(cli.jwt);
                        clockTimestamp = Math.floor(Date.now() / 1000);
                        if (!((payload.exp - clockTimestamp) < 60)) return [3 /*break*/, 5];
                        Logger_1.Logger.instanse.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 4:
                        tuser = _a.sent();
                        if (tuser != null) {
                            span.addEvent("Token for " + cli.id + "/" + cli.user.name + "/" + cli.clientagent + " expires in less than 1 minute, send new jwt to client");
                            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 = 5;
                    case 5: return [3 /*break*/, 7];
                    case 6:
                        error_1 = _a.sent();
                        span.recordException(error_1);
                        console.error(error_1);
                        cli.Close();
                        return [3 /*break*/, 7];
                    case 7:
                        now = new Date();
                        seconds = (now.getTime() - cli.lastheartbeat.getTime()) / 1000;
                        if (seconds >= Config_1.Config.client_heartbeat_timeout) {
                            if (cli.user != null) {
                                span.addEvent("client " + cli.id + "/" + cli.user.name + "/" + cli.clientagent + " timeout, close down");
                                Logger_1.Logger.instanse.info("client " + cli.id + "/" + cli.user.name + "/" + cli.clientagent + " timeout, close down");
                            }
                            else {
                                span.addEvent("client not signed/" + cli.id + "/" + cli.clientagent + " timeout, close down");
                                Logger_1.Logger.instanse.info("client not signed/" + cli.id + "/" + cli.clientagent + " timeout, close down");
                            }
                            cli.Close();
                        }
                        cli.ping(span);
                        if (!cli.connected() && cli.queuecount() == 0 && cli.streamcount() == 0) {
                            if (cli.user != null) {
                                Logger_1.Logger.instanse.info("removing disconnected client " + cli.id + "/" + cli.user.name + "/" + cli.clientagent);
                                span.addEvent("removing disconnected client " + cli.id + "/" + cli.user.name + "/" + cli.clientagent);
                            }
                            else {
                                Logger_1.Logger.instanse.info("removing disconnected client " + cli.id + "/" + cli.clientagent + " timeout, close down");
                                span.addEvent("removing disconnected client " + cli.id + "/" + cli.clientagent + " timeout, close down");
                            }
                            WebSocketServer._clients.splice(i, 1);
                        }
                        _a.label = 8;
                    case 8:
                        i--;
                        return [3 /*break*/, 2];
                    case 9:
                        if (count !== WebSocketServer._clients.length) {
                            Logger_1.Logger.instanse.info("new client count: " + WebSocketServer._clients.length);
                            span.setAttribute("clientcount", WebSocketServer._clients.length);
                        }
                        p_all_1 = {};
                        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)) {
                                        if (!openflow_api_1.NoderedUtil.IsNullUndefinded(WebSocketServer.p_all)) {
                                            if (openflow_api_1.NoderedUtil.IsNullUndefinded(p_all_1[cli.clientagent]))
                                                p_all_1[cli.clientagent] = 0;
                                            p_all_1[cli.clientagent] += 1;
                                        }
                                    }
                                    // Lets assume only robots register queues ( not true )
                                    if (cli.clientagent == "openrpa") {
                                        Config_1.Config.db.synRawUpdateOne("users", { _id: cli.user._id }, { $set: { _rpaheartbeat: new Date(new Date().toISOString()), _heartbeat: new Date(new Date().toISOString()) } }, Config_1.Config.prometheus_measure_onlineuser, null);
                                    }
                                    if (cli.clientagent == "nodered") {
                                        Config_1.Config.db.synRawUpdateOne("users", { _id: cli.user._id }, { $set: { _noderedheartbeat: new Date(new Date().toISOString()), _heartbeat: new Date(new Date().toISOString()) } }, Config_1.Config.prometheus_measure_onlineuser, null);
                                    }
                                    if (cli.clientagent == "webapp" || cli.clientagent == "aiotwebapp") {
                                        Config_1.Config.db.synRawUpdateOne("users", { _id: cli.user._id }, { $set: { _webheartbeat: new Date(new Date().toISOString()), _heartbeat: new Date(new Date().toISOString()) } }, Config_1.Config.prometheus_measure_onlineuser, null);
                                    }
                                    if (cli.clientagent == "powershell") {
                                        Config_1.Config.db.synRawUpdateOne("users", { _id: cli.user._id }, { $set: { _powershellheartbeat: new Date(new Date().toISOString()), _heartbeat: new Date(new Date().toISOString()) } }, Config_1.Config.prometheus_measure_onlineuser, null);
                                    }
                                    if (cli.clientagent == "mobileapp" || cli.clientagent == "aiotmobileapp") {
                                        Config_1.Config.db.synRawUpdateOne("users", { _id: cli.user._id }, { $set: { _webheartbeat: new Date(new Date().toISOString()), _mobilheartbeat: new Date(new Date().toISOString()), _heartbeat: new Date(new Date().toISOString()) } }, Config_1.Config.prometheus_measure_onlineuser, null);
                                    }
                                    else {
                                        // Should proberly turn this a little down, so we dont update all online users every 10th second
                                        Config_1.Config.db.synRawUpdateOne("users", { _id: cli.user._id }, { $set: { _heartbeat: new Date(new Date().toISOString()) } }, Config_1.Config.prometheus_measure_onlineuser, null);
                                    }
                                }
                            }
                            catch (error) {
                                span.recordException(error);
                                console.error(error);
                            }
                        }
                        if (!openflow_api_1.NoderedUtil.IsNullUndefinded(WebSocketServer.p_all)) {
                            WebSocketServer.p_all.clear();
                            keys = Object.keys(p_all_1);
                            keys.forEach(function (key) {
                                WebSocketServer.p_all.bind(__assign(__assign({}, Logger_1.Logger.otel.defaultlabels), { agent: key })).update(p_all_1[key]);
                            });
                        }
                        return [3 /*break*/, 12];
                    case 10:
                        error_2 = _a.sent();
                        span.recordException(error_2);
                        throw error_2;
                    case 11:
                        Logger_1.Logger.otel.endSpan(span);
                        return [7 /*endfinally*/];
                    case 12: return [2 /*return*/];
                }
            });
        });
    };
    return WebSocketServer;
}());
exports.WebSocketServer = WebSocketServer;
//# sourceMappingURL=WebSocketServer.js.map