"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "TestPrinterSocketStore", {
    enumerable: true,
    get: function() {
        return TestPrinterSocketStore;
    }
});
const _promises = require("node:timers/promises");
const _validators = require("../handlers/validators");
const _createtestprintervalidation = require("./validation/create-test-printer.validation");
const _octoprintwebsocketadapter = require("../services/octoprint/octoprint-websocket.adapter");
const _serverconstants = require("../server.constants");
const _errorutils = require("../utils/error.utils");
const _node = require("@sentry/node");
const _socketstatetype = require("../shared/dtos/socket-state.type");
const _moonrakerconstants = require("../services/moonraker/constants/moonraker.constants");
const _bambumqttadapter = require("../services/bambu/bambu-mqtt.adapter");
const _prusalinkconstants = require("../services/prusa-link/constants/prusalink.constants");
const _eventconstants = require("../constants/event.constants");
const TEST_PRINTER_ID_BASE = 100000;
let testPrinterIdCounter = 0;
class TestPrinterSocketStore {
    socketFactory;
    socketIoGateway;
    eventEmitter2;
    testSocket;
    logger;
    constructor(loggerFactory, socketFactory, socketIoGateway, eventEmitter2){
        this.socketFactory = socketFactory;
        this.socketIoGateway = socketIoGateway;
        this.eventEmitter2 = eventEmitter2;
        this.logger = loggerFactory(TestPrinterSocketStore.name);
    }
    async setupTestPrinter(correlationToken, printer) {
        if (this.testSocket) {
            this.testSocket.close();
            delete this.testSocket;
        }
        const validatedData = await (0, _validators.validateInput)(printer, _createtestprintervalidation.createTestPrinterSchema);
        validatedData.enabled = true;
        const testPrinterId = TEST_PRINTER_ID_BASE + ++testPrinterIdCounter;
        this.testSocket = this.socketFactory.createInstance(printer.printerType);
        this.testSocket.registerCredentials({
            printerId: testPrinterId,
            loginDto: {
                apiKey: printer.apiKey,
                username: printer.username,
                password: printer.password,
                printerURL: printer.printerURL,
                printerType: printer.printerType
            }
        });
        const testEvents = [
            (0, _octoprintwebsocketadapter.octoPrintEvent)(_octoprintwebsocketadapter.WsMessage.WS_STATE_UPDATED),
            (0, _octoprintwebsocketadapter.octoPrintEvent)(_octoprintwebsocketadapter.WsMessage.API_STATE_UPDATED),
            (0, _octoprintwebsocketadapter.octoPrintEvent)(_octoprintwebsocketadapter.WsMessage.WS_CLOSED),
            (0, _octoprintwebsocketadapter.octoPrintEvent)(_octoprintwebsocketadapter.WsMessage.WS_OPENED),
            (0, _octoprintwebsocketadapter.octoPrintEvent)(_octoprintwebsocketadapter.WsMessage.WS_ERROR),
            (0, _moonrakerconstants.moonrakerEvent)(_octoprintwebsocketadapter.WsMessage.WS_STATE_UPDATED),
            (0, _moonrakerconstants.moonrakerEvent)(_octoprintwebsocketadapter.WsMessage.API_STATE_UPDATED),
            (0, _moonrakerconstants.moonrakerEvent)(_octoprintwebsocketadapter.WsMessage.WS_CLOSED),
            (0, _moonrakerconstants.moonrakerEvent)(_octoprintwebsocketadapter.WsMessage.WS_OPENED),
            (0, _moonrakerconstants.moonrakerEvent)(_octoprintwebsocketadapter.WsMessage.WS_ERROR),
            (0, _bambumqttadapter.bambuEvent)(_octoprintwebsocketadapter.WsMessage.WS_STATE_UPDATED),
            (0, _bambumqttadapter.bambuEvent)(_octoprintwebsocketadapter.WsMessage.API_STATE_UPDATED),
            (0, _bambumqttadapter.bambuEvent)(_octoprintwebsocketadapter.WsMessage.WS_CLOSED),
            (0, _bambumqttadapter.bambuEvent)(_octoprintwebsocketadapter.WsMessage.WS_OPENED),
            (0, _bambumqttadapter.bambuEvent)(_octoprintwebsocketadapter.WsMessage.WS_ERROR),
            (0, _prusalinkconstants.prusaLinkEvent)(_octoprintwebsocketadapter.WsMessage.WS_STATE_UPDATED),
            (0, _prusalinkconstants.prusaLinkEvent)(_octoprintwebsocketadapter.WsMessage.API_STATE_UPDATED),
            (0, _prusalinkconstants.prusaLinkEvent)(_octoprintwebsocketadapter.WsMessage.WS_CLOSED),
            (0, _prusalinkconstants.prusaLinkEvent)(_octoprintwebsocketadapter.WsMessage.WS_OPENED),
            (0, _prusalinkconstants.prusaLinkEvent)(_octoprintwebsocketadapter.WsMessage.WS_ERROR)
        ];
        const listener = ({ event, payload, printerId })=>{
            if (printerId !== testPrinterId) {
                return;
            }
            this.socketIoGateway.send("test-printer-state", {
                event,
                payload,
                correlationToken
            });
        };
        testEvents.forEach((te)=>{
            this.eventEmitter2.on(te, listener);
        });
        try {
            this.logger.log("Test API calls for authentication and session");
            await this.testSocket.setupSocketSession();
            this.logger.log("Test socket connection started");
            const promise = new Promise(async (resolve, reject)=>{
                if (!this.testSocket) {
                    this.logger.error("Aborting test as testSocket is undefined.");
                    return;
                }
                this.testSocket.open();
                for await (const _startTime of (0, _promises.setInterval)(100)){
                    if (!this.testSocket) {
                        this.logger.warn("Test without socket, rejecting");
                        reject(new Error("Test without socket, rejecting"));
                        return;
                    }
                    if (this.testSocket.socketState === _socketstatetype.SOCKET_STATE.authenticated) {
                        this.logger.log("Test completed successfully, resolving");
                        resolve(true);
                        break;
                    }
                }
            });
            await Promise.race([
                promise,
                (0, _promises.setTimeout)(_serverconstants.AppConstants.defaultWebsocketHandshakeTimeout)
            ]);
            this.logger.log("Test finalized");
        } catch (e) {
            this.logger.error(`Test harness error ${(0, _errorutils.errorSummary)(e)}`);
            (0, _node.captureException)(e);
        } finally{
            this.testSocket.disallowEmittingEvents();
            if (this.testSocket) {
                this.testSocket.close();
            }
            this.eventEmitter2.emit(_eventconstants.printerEvents.printersDeleted, {
                printerIds: [
                    testPrinterId
                ]
            });
            delete this.testSocket;
            testEvents.forEach((te)=>{
                this.eventEmitter2.off(te, listener);
            });
        }
    }
}

//# sourceMappingURL=test-printer-socket.store.js.map