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

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

    if (printerData.name) {
        createLog(
            "debug",
            "printerState",
            "ocp",
            `${printerData.name}: unpaused printed`
        );
    } else {
        createLog(
            "error",
            "printerState",
            "ocp",
            `Unknown name on printer was just unpaused, Body sent over: ${JSON.stringify(
                printerData
            )}`
        );
    }

    return new Promise((resolve, reject) => {
        pause.connect(printerData.port, printerData.ipAddress, async () => {
            // console.log("Connected to printer");
            pause.write("~PS");
            pause.end();
        });

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

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

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