import { eq, sql } from "drizzle-orm";
import { db } from "../../../../../database/dbclient.js";
import { printerData } from "../../../../../database/schema/printers.js";
import { createLog } from "../../../logger/logger.js";

export const printStatus = [
    { code: 1, text: "Printing" },
    { code: 2, text: "Pending labels" },
    { code: 3, text: "Printing to fast" },
    { code: 4, text: "Creating label" },
    { code: 5, text: "Waiting" },
    { code: 6, text: "Printer Paused" },
    { code: 7, text: "Printer error" },
    {
        code: 8,
        text: "First time printing",
    },
    {
        code: 9,
        text: "Offline",
    },
];

export const printerUpdate = async (printer: any, status: any) => {
    /**
     * Updates the status of the printer.
     */

    // get current time
    let pd = {};
    const currentTime = sql`NOW()`;

    if (status === 3) {
        pd = {
            status: status,
            statusText: printStatus.filter((c) => c.code === status)[0]?.text,
        };
    } else if (status === 6) {
        pd = {
            status: status,
            statusText: printStatus.filter((c) => c.code === status)[0]?.text,
        };
    } else {
        pd = {
            lastTimePrinted: currentTime,
            status: status,
            statusText: printStatus.filter((c) => c.code === status)[0]?.text,
        };
    }

    if (printer.humanReadableId) {
        try {
            await db
                .update(printerData)
                .set(pd)
                .where(
                    eq(printerData.humanReadableId, printer.humanReadableId)
                );
        } catch (error) {
            createLog("error", "ocp", "ocp", `Error updating printer state`);
        }
    }

    // console.log(printerUpdate.name);
    return;
};
