import { createLog } from "../../../../../logger/logger.js";
import { pickedup } from "../../../../../ocme/controller/pickedup.js";
import { triggerScanner } from "../../../../../ocme/controller/triggerCamera.js";
import { serverSettings } from "../../../../../server/controller/settings/getSettings.js";

let lastProcessedTimestamp = 0;

export const palletSendTag = async (tagData: any) => {
    /**
     * Reads the tag data from the Dyco PLC and processes it based on the feedback.
     * We will only trigger the camera and removal of pending tags
     */

    const ocmeActive = serverSettings.filter((n) => n.name === "ocmeService");

    const tagTime = new Date(tagData.state.timestamp).getTime();

    // Only process if this is a new timestamp within the last 5 seconds
    if (
        tagTime !== lastProcessedTimestamp &&
        Date.now() - tagTime <= 5000 &&
        tagData.value &&
        ocmeActive[0].value === "1"
    ) {
        lastProcessedTimestamp = tagTime;
        //console.log(tagData.state.timestamp);
        createLog(
            "info",
            "dyco",
            "ocp",
            `Station 6 is ${tagData.value ? "full" : "empty"}`
        );

        // take the picture
        setTimeout(async () => {
            const scan: any = await triggerScanner();
            if (!scan.success) {
                createLog(
                    "error",
                    "dyco",
                    "ocp",
                    `Scanner failed to take a picture trying one more time in 10 seconds`
                );
                setTimeout(async () => {
                    await triggerScanner();
                }, 10 * 1000);
            }
        }, 15 * 1000);
    }

    if (
        tagTime !== lastProcessedTimestamp &&
        Date.now() - tagTime <= 5000 &&
        !tagData.value &&
        ocmeActive[0].value === "1"
    ) {
        await pickedup({ runningNr: 1234, all: true, areaFrom: "wrapper_1" });
    }
};
