"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "PrinterWebsocketRestoreTask", {
    enumerable: true,
    get: function() {
        return PrinterWebsocketRestoreTask;
    }
});
const _errorutils = require("../utils/error.utils");
const _node = require("@sentry/node");
const _apistatetype = require("../shared/dtos/api-state.type");
const _printerapiinterface = require("../services/printer-api.interface");
class PrinterWebsocketRestoreTask {
    printerSocketStore;
    octoprintClient;
    logger;
    constructor(loggerFactory, printerSocketStore, octoprintClient){
        this.printerSocketStore = printerSocketStore;
        this.octoprintClient = octoprintClient;
        this.logger = loggerFactory(PrinterWebsocketRestoreTask.name);
    }
    async run() {
        const existingSockets = this.printerSocketStore.listPrinterSockets();
        for (const socket of existingSockets){
            if (socket.printerType !== _printerapiinterface.OctoprintType) {
                continue;
            }
            try {
                if (socket.isClosedOrAborted()) {
                    socket.close();
                    socket.resetSocketState();
                    this.logger.warn("Socket was closed or aborted, manually removing it");
                    continue;
                }
            } catch (e) {
                (0, _node.captureException)(e);
                this.logger.error(`Resetting WebSocket socket failed for printer with error '${(0, _errorutils.errorSummary)(e)}'`, e.stack);
                continue;
            }
            if (socket.apiState !== _apistatetype.API_STATE.unset && !socket.lastMessageReceivedTimestamp || socket.lastMessageReceivedTimestamp && Date.now() - socket.lastMessageReceivedTimestamp > 10 * 1000) {
                const result = await this.octoprintClient.getConnection(socket.login);
                try {
                    if (result.data?.current?.state !== "Closed") {
                        this.logger.warn(`Silence was detected, but the OctoPrint current connection was not closed. Connection state ${result.data?.current?.state}`);
                    }
                } catch (e) {
                    this.logger.error(`Silence was detected, but Websocket was not closed/aborted and API could not be called`);
                }
            }
        }
    }
}

//# sourceMappingURL=printer-websocket-restore.task.js.map