import net from "net";
import { db } from "../../../../database/dbclient.js";
import { settings } from "../../../../database/schema/settings.js";
import { eq } from "drizzle-orm";
import { createLog } from "../../logger/logger.js";

export const triggerScanner = async () => {
    const camera = new net.Socket();
    let setting = await db
        .select()
        .from(settings)
        .where(eq(settings.name, "zebraScanners"));
    if (setting.length === 0) {
        return {
            success: false,
            message: "Looks like the setting is missing.",
        };
    }
    const scannerData = JSON.parse(setting[0]?.value);
    let data = scannerData.filter((n: any) => n.name === "wrapper1");

    if (data.length === 0) {
        return {
            success: false,
            message: "Looks like the scanner is missing.",
        };
    }
    let port = data[0]?.port;

    createLog(
        "info",
        "wrapperScanner",
        "ocme",
        `End of line Camera was triggered`
    );
    return new Promise((resolve, reject) => {
        camera.connect(port, data[0].ip, async () => {
            createLog("info", "wrapperScanner", "ocme", `Triggered`);
            camera.write("TRIGGER", "utf8");
            camera.end();
            setTimeout(() => {
                if (!camera.destroyed) {
                    camera.destroy();
                }
            }, 500);
            resolve({ success: true, message: "Camera was triggered." });
        });

        camera.on("end", () => {
            setTimeout(() => {
                if (!camera.destroyed) {
                    createLog(
                        "info",
                        "ocme",
                        "ocme",
                        `Ocme Camera was destroyed, on trigger status`
                    );
                    camera.destroy();
                }
            }, 1000);
        });

        camera.on("error", (error) => {
            createLog("error", "wrapperScanner", "ocme", `${error}`);
            resolve({
                success: false,
                message: `There was an error triggering the camera: ${JSON.stringify(
                    error
                )}`,
            });
        });
    });
};
