"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "PrusaLinkHttpPollingAdapter", {
    enumerable: true,
    get: function() {
        return PrusaLinkHttpPollingAdapter;
    }
});
const _printerapiinterface = require("../printer-api.interface");
const _socketstatetype = require("../../shared/dtos/socket-state.type");
const _apistatetype = require("../../shared/dtos/api-state.type");
const _errorutils = require("../../utils/error.utils");
const _prusalinkconstants = require("./constants/prusalink.constants");
const _octoprintwebsocketadapter = require("../octoprint/octoprint-websocket.adapter");
const defaultLog = {
    adapter: "prusa-link"
};
class PrusaLinkHttpPollingAdapter {
    prusaLinkApi;
    eventEmitter2;
    printerType = _printerapiinterface.PrusaLinkType;
    printerId;
    login;
    socketState;
    apiState;
    lastMessageReceivedTimestamp;
    refreshPrinterCurrentInterval;
    eventEmittingAllowed = true;
    constructor(loggerFactory, prusaLinkApi, eventEmitter2){
        this.prusaLinkApi = prusaLinkApi;
        this.eventEmitter2 = eventEmitter2;
        this.logger = loggerFactory(PrusaLinkHttpPollingAdapter.name);
    }
    allowEmittingEvents() {
        this.eventEmittingAllowed = true;
    }
    disallowEmittingEvents() {
        this.eventEmittingAllowed = false;
    }
    needsReopen() {
        return !this.refreshPrinterCurrentInterval;
    }
    needsSetup() {
        return !this.refreshPrinterCurrentInterval;
    }
    needsReauth() {
        throw new Error("Method not implemented.");
    }
    isClosedOrAborted() {
        throw new Error("Method not implemented.");
    }
    reauthSession() {
        throw new Error("Method not implemented.");
    }
    registerCredentials(socketLogin) {
        this.login = socketLogin.loginDto;
        this.printerId = socketLogin.printerId;
    }
    open() {
        this.startPolling();
    }
    close() {
        this.logger.debug("Polling adapter attempting stoppage.", this.logMeta());
        this.stopPolling();
    }
    setupSocketSession() {
        this.logger.warn("SetupSocketSession", defaultLog);
        return Promise.resolve();
    }
    resetSocketState() {
        this.logger.warn("ResetSocketState", defaultLog);
    }
    startPolling() {
        this.stopPolling();
        this.logger.debug("Polling adapter starting, setting interval.", this.logMeta());
        this.refreshPrinterCurrentInterval = setInterval(async ()=>{
            if (!this.printerId) {
                this.logger.warn("Printer ID is not set, skipping status check.", this.logMeta());
                this.stopPolling();
                return;
            }
            this.updateSocketState(_socketstatetype.SOCKET_STATE.opening);
            try {
                this.prusaLinkApi.login = {
                    printerURL: this.login.printerURL,
                    username: this.login.username,
                    password: this.login.password,
                    apiKey: "",
                    printerType: _printerapiinterface.PrusaLinkType
                };
                this.updateSocketState(_socketstatetype.SOCKET_STATE.authenticating);
                const printerState = await this.prusaLinkApi.getPrinterState();
                if (printerState.state.flags?.link_state && printerState.state.flags?.link_state !== "PRINTING") {
                    printerState.state.text = printerState.state.flags.link_state;
                }
                const jobState = await this.prusaLinkApi.getJobState();
                this.updateSocketState(_socketstatetype.SOCKET_STATE.authenticated);
                this.updateApiState(_apistatetype.API_STATE.responding);
                await this.emitEvent("current", {
                    ...printerState,
                    job: jobState.job,
                    progress: {
                        printTime: jobState.progress?.printTime,
                        printTimeLeft: jobState.progress?.printTimeLeft,
                        completion: jobState.progress?.completion * 100
                    }
                });
            } catch (error) {
                this.updateSocketState(_socketstatetype.SOCKET_STATE.error);
                this.logger.error(`Failed to fetch PrusaLink status ${(0, _errorutils.errorSummary)(error)}`, this.logMeta());
            }
        }, 5000);
    }
    stopPolling() {
        if (this.refreshPrinterCurrentInterval) {
            this.logger.debug("Polling adapter stopping, clearing interval.", this.logMeta());
            clearInterval(this.refreshPrinterCurrentInterval);
            this.refreshPrinterCurrentInterval = undefined;
            this.updateSocketState(_socketstatetype.SOCKET_STATE.closed);
        }
    }
    async emitEvent(event, payload) {
        if (!this.eventEmittingAllowed) {
            return;
        }
        this.logger.debug(`Emitting event ${(0, _prusalinkconstants.prusaLinkEvent)(event)}`, this.logMeta());
        await this.eventEmitter2.emitAsync((0, _prusalinkconstants.prusaLinkEvent)(event), {
            event,
            payload,
            printerId: this.printerId,
            printerType: _printerapiinterface.PrusaLinkType
        });
    }
    emitEventSync(event, payload) {
        if (!this.eventEmittingAllowed) {
            return;
        }
        this.eventEmitter2.emit((0, _prusalinkconstants.prusaLinkEvent)(event), {
            event,
            payload,
            printerId: this.printerId,
            printerType: _printerapiinterface.PrusaLinkType
        });
    }
    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);
    }
    logMeta() {
        return defaultLog;
    }
}

//# sourceMappingURL=prusa-link-http-polling.adapter.js.map