import net from "net";
import { createLog } from "../../logger/logger.js";

export const pausePrinter = async (printerData: any) => {
    const pause = new net.Socket();

    if (printerData.name) {
        createLog(
            "debug",
            "printerState",
            "ocp",
            `${printerData.name}: paused printed`
        );
    } else {
        createLog(
            "error",
            "printerState",
            "ocp",
            `Unknown name on printer was just paused, Body sent over: ${printerData.name}`
        );
    }
    return new Promise((resolve, reject) => {
        pause.connect(printerData.port, printerData.ipAddress, async () => {
            // console.log("Connected to printer");
            pause.write("~PP");
            pause.end();
        });

        pause.on("error", (error) => {
            createLog(
                "error",
                "printerState",
                "ocp",
                `There was an error pausing the printer: ${JSON.stringify(
                    error
                )}`
            );
            reject({
                success: true,
                message: "There was an error pausing the printer",
                data: error,
            });
        });

        pause.on("end", () => {
            setTimeout(() => {
                if (!pause.destroyed) {
                    createLog(
                        "info",
                        "printerState",
                        "ocp",
                        `${printerData.name}: was force closed, in pausing trigger`
                    );
                    pause.destroy();
                }
            }, 1000);
        });

        resolve({
            success: true,
            message: `${
                printerData?.name || printerData.ipAddress
            }  Printer was paused`,
        });
    });
};
