"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
function _export(target, all) {
    for(var name in all)Object.defineProperty(target, name, {
        enumerable: true,
        get: Object.getOwnPropertyDescriptor(all, name).get
    });
}
_export(exports, {
    get BambuMqttAdapter () {
        return BambuMqttAdapter;
    },
    get bambuEvent () {
        return bambuEvent;
    }
});
const _mqtt = /*#__PURE__*/ _interop_require_default(require("mqtt"));
const _socketstatetype = require("../../shared/dtos/socket-state.type");
const _apistatetype = require("../../shared/dtos/api-state.type");
const _printerapiinterface = require("../printer-api.interface");
const _octoprintwebsocketadapter = require("../octoprint/octoprint-websocket.adapter");
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
const bambuEvent = (event)=>`bambu.${event}`;
class BambuMqttAdapter {
    logger;
    settingsStore;
    eventEmitter2;
    printerType = _printerapiinterface.BambuType;
    printerId;
    socketState = _socketstatetype.SOCKET_STATE.unopened;
    apiState = _apistatetype.API_STATE.unset;
    login;
    lastMessageReceivedTimestamp = null;
    mqttClient = null;
    host = null;
    accessCode = null;
    serial = null;
    lastState = null;
    isConnecting = false;
    eventsAllowed = true;
    constructor(settingsStore, loggerFactory, eventEmitter2){
        this.settingsStore = settingsStore;
        this.eventEmitter2 = eventEmitter2;
        this.logger = loggerFactory(BambuMqttAdapter.name);
    }
    registerCredentials(socketLogin) {
        const { printerId, loginDto } = socketLogin;
        this.printerId = printerId;
        this.login = loginDto;
        this.host = loginDto.printerURL?.replace(/^https?:\/\//, "");
        this.accessCode = loginDto.password || null;
        this.serial = loginDto.username || null;
    }
    needsReopen() {
        const isApiOnline = this.apiState === _apistatetype.API_STATE.responding;
        return isApiOnline && (this.socketState === _socketstatetype.SOCKET_STATE.closed || this.socketState === _socketstatetype.SOCKET_STATE.error);
    }
    needsSetup() {
        return this.socketState === _socketstatetype.SOCKET_STATE.unopened;
    }
    needsReauth() {
        return false;
    }
    isClosedOrAborted() {
        return this.socketState === _socketstatetype.SOCKET_STATE.closed || this.socketState === _socketstatetype.SOCKET_STATE.aborted;
    }
    async reauthSession() {
        this.logger.debug("reauthSession called but not needed for Bambu");
    }
    open() {
        if (!this.host || !this.accessCode || !this.serial) {
            throw new Error("Cannot open connection: credentials not registered");
        }
        this.connect(this.host, this.accessCode, this.serial);
    }
    close() {
        this.disconnect().catch((err)=>{
            this.logger.error("Error during MQTT disconnect:", err);
        });
    }
    async setupSocketSession() {
        if (!this.host || !this.accessCode || !this.serial) {
            this.updateSocketState(_socketstatetype.SOCKET_STATE.aborted);
            this.updateApiState(_apistatetype.API_STATE.noResponse);
            throw new Error("Credentials not properly registered");
        }
        this.updateSocketState(_socketstatetype.SOCKET_STATE.opening);
        this.updateApiState(_apistatetype.API_STATE.responding);
    }
    allowEmittingEvents() {
        this.eventsAllowed = true;
    }
    disallowEmittingEvents() {
        this.eventsAllowed = false;
    }
    connect(host, accessCode, serial) {
        if (this.mqttClient?.connected) {
            this.logger.debug("MQTT already connected");
            this.updateSocketState(_socketstatetype.SOCKET_STATE.opened);
            return;
        }
        if (this.isConnecting) {
            this.logger.warn("Connection already in progress");
            return;
        }
        this.host = host;
        this.accessCode = accessCode;
        this.serial = serial;
        this.isConnecting = true;
        this.updateSocketState(_socketstatetype.SOCKET_STATE.opening);
        const mqttUrl = `mqtts://${host}:8883`;
        const timeout = this.settingsStore.getTimeoutSettings().apiTimeout;
        this.logger.log(`Connecting to Bambu MQTT at ${mqttUrl}`);
        const connectionTimeout = setTimeout(()=>{
            this.isConnecting = false;
            this.updateSocketState(_socketstatetype.SOCKET_STATE.error);
            this.logger.error("MQTT connection timeout");
            if (this.mqttClient) {
                this.mqttClient.end(true);
            }
        }, timeout);
        try {
            this.mqttClient = _mqtt.default.connect(mqttUrl, {
                username: "bblp",
                password: accessCode,
                clientId: `fdm_monster_${serial}_${Date.now()}`,
                protocol: "mqtts",
                connectTimeout: timeout,
                reconnectPeriod: 0,
                keepalive: 60,
                rejectUnauthorized: false
            });
            this.mqttClient.on("connect", ()=>{
                clearTimeout(connectionTimeout);
                this.isConnecting = false;
                this.updateSocketState(_socketstatetype.SOCKET_STATE.authenticated);
                this.updateApiState(_apistatetype.API_STATE.responding);
                this.logger.log("MQTT connected successfully");
                const reportTopic = `device/${serial}/report`;
                this.mqttClient.subscribe(reportTopic, {
                    qos: 0
                }, (err)=>{
                    if (err) {
                        this.logger.error(`Failed to subscribe to ${reportTopic}:`, err);
                        this.updateSocketState(_socketstatetype.SOCKET_STATE.error);
                    } else {
                        this.logger.debug(`Subscribed to ${reportTopic}`);
                    }
                });
            });
            this.mqttClient.on("error", (error)=>{
                this.isConnecting = false;
                this.updateSocketState(_socketstatetype.SOCKET_STATE.error);
                this.emitEvent(_octoprintwebsocketadapter.WsMessage.WS_ERROR, error.message).catch(()=>{});
                this.logger.error("MQTT error:", error);
            });
            this.mqttClient.on("message", (topic, message)=>{
                this.lastMessageReceivedTimestamp = Date.now();
                this.handleMessage(topic, message);
            });
            this.mqttClient.on("disconnect", ()=>{
                this.updateSocketState(_socketstatetype.SOCKET_STATE.closed);
                this.emitEvent(_octoprintwebsocketadapter.WsMessage.WS_CLOSED, "disconnected").catch(()=>{});
                this.logger.warn("MQTT disconnected");
            });
            this.mqttClient.on("reconnect", ()=>{
                this.updateSocketState(_socketstatetype.SOCKET_STATE.opening);
                this.logger.debug("MQTT reconnecting...");
            });
            this.mqttClient.on("close", ()=>{
                this.updateSocketState(_socketstatetype.SOCKET_STATE.closed);
                this.emitEvent(_octoprintwebsocketadapter.WsMessage.WS_CLOSED, "connection closed").catch(()=>{});
                this.logger.debug("MQTT connection closed");
                this.cleanup();
            });
        } catch (error) {
            clearTimeout(connectionTimeout);
            this.isConnecting = false;
            this.updateSocketState(_socketstatetype.SOCKET_STATE.error);
            this.logger.error("Failed to create MQTT client:", error);
            this.cleanup();
        }
    }
    async disconnect() {
        if (!this.mqttClient) {
            this.updateSocketState(_socketstatetype.SOCKET_STATE.closed);
            return;
        }
        this.logger.log("Disconnecting MQTT");
        this.updateSocketState(_socketstatetype.SOCKET_STATE.closed);
        return new Promise((resolve)=>{
            if (this.mqttClient?.connected) {
                this.mqttClient.end(false, {}, ()=>{
                    this.cleanup();
                    resolve();
                });
            } else {
                this.cleanup();
                resolve();
            }
        });
    }
    getLastState() {
        return this.lastState;
    }
    async sendCommand(payload) {
        if (!this.mqttClient?.connected) {
            throw new Error("MQTT not connected");
        }
        if (!this.serial) {
            throw new Error("Serial number not set");
        }
        const requestTopic = `device/${this.serial}/request`;
        const message = JSON.stringify(payload);
        return new Promise((resolve, reject)=>{
            this.mqttClient.publish(requestTopic, message, {
                qos: 0
            }, (err)=>{
                if (err) {
                    this.logger.error("Failed to send command:", err);
                    reject(err);
                } else {
                    this.logger.debug("Command sent:", payload);
                    resolve();
                }
            });
        });
    }
    async startPrint(filename) {
        await this.sendCommand({
            print: {
                command: "project_file",
                param: filename,
                url: `file:///sdcard/${filename}`,
                subtask_name: filename,
                sequence_id: String(Date.now())
            }
        });
    }
    async pausePrint() {
        await this.sendCommand({
            print: {
                command: "pause",
                sequence_id: String(Date.now())
            }
        });
    }
    async resumePrint() {
        await this.sendCommand({
            print: {
                command: "resume",
                sequence_id: String(Date.now())
            }
        });
    }
    async stopPrint() {
        await this.sendCommand({
            print: {
                command: "stop",
                sequence_id: String(Date.now())
            }
        });
    }
    async sendGcode(gcode) {
        await this.sendCommand({
            print: {
                command: "gcode_line",
                param: gcode,
                sequence_id: String(Date.now())
            }
        });
    }
    resetSocketState() {
        this.lastState = null;
    }
    updateSocketState(state) {
        this.socketState = state;
        this.emitEventSync(_octoprintwebsocketadapter.WsMessage.WS_STATE_UPDATED, state);
    }
    updateApiState(state) {
        this.apiState = state;
        this.emitEventSync(_octoprintwebsocketadapter.WsMessage.API_STATE_UPDATED, state);
    }
    async emitEvent(event, payload) {
        if (!this.eventsAllowed) {
            return;
        }
        await this.eventEmitter2.emitAsync(bambuEvent(event), {
            event,
            payload,
            printerId: this.printerId,
            printerType: _printerapiinterface.BambuType
        });
    }
    emitEventSync(event, payload) {
        if (!this.eventsAllowed) {
            return;
        }
        this.eventEmitter2.emit(bambuEvent(event), {
            event,
            payload,
            printerId: this.printerId,
            printerType: _printerapiinterface.BambuType
        });
    }
    transformStateToCurrentMessage(state) {
        const isPrinting = state.gcode_state === "PRINTING" || state.mc_print_stage === "printing";
        const isPaused = state.mc_print_stage === "paused";
        const isPausedText = isPaused ? "Paused" : "Printing";
        return {
            state: {
                text: isPrinting ? isPausedText : "Operational",
                flags: {
                    operational: true,
                    printing: isPrinting && !isPaused,
                    paused: isPaused,
                    ready: !isPrinting,
                    error: state.print_error !== 0,
                    cancelling: false,
                    pausing: false,
                    sdReady: true,
                    closedOrError: false
                }
            },
            temps: [
                {
                    time: Date.now(),
                    tool0: {
                        actual: state.nozzle_temper || 0,
                        target: state.nozzle_target_temper || 0
                    },
                    bed: {
                        actual: state.bed_temper || 0,
                        target: state.bed_target_temper || 0
                    },
                    chamber: {
                        actual: state.chamber_temper || 0,
                        target: 0
                    }
                }
            ],
            progress: {
                completion: state.mc_percent || 0,
                printTime: null,
                printTimeLeft: state.mc_remaining_time ? state.mc_remaining_time * 60 : null
            },
            job: {
                file: {
                    name: state.gcode_file || state.subtask_name || null
                }
            },
            currentZ: state.layer_num || null,
            offsets: {},
            resends: {
                count: 0,
                transmitted: 0,
                ratio: 0
            },
            logs: [],
            messages: []
        };
    }
    handleMessage(topic, message) {
        try {
            const payload = JSON.parse(message.toString());
            if (topic.endsWith("/report") && payload.print) {
                this.lastState = payload.print;
                const currentMessage = this.transformStateToCurrentMessage(this.lastState);
                const combinedPayload = {
                    ...currentMessage,
                    print: payload.print
                };
                this.emitEvent("current", combinedPayload).catch((err)=>{
                    this.logger.error("Failed to emit current event:", err);
                });
            }
        } catch (error) {
            this.logger.error("Failed to parse MQTT message:", error);
        }
    }
    cleanup() {
        if (this.mqttClient) {
            this.mqttClient.removeAllListeners();
            this.mqttClient = null;
        }
        this.isConnecting = false;
        this.lastState = null;
    }
}

//# sourceMappingURL=bambu-mqtt.adapter.js.map