import { db } from "../../../../../../../database/dbclient.js";
import { settings } from "../../../../../../../database/schema/settings.js";
import { tryCatch } from "../../../../../../globalUtils/tryCatch.js";
import { createLog } from "../../../../../logger/logger.js";
import { readTags } from "../../../../../rfid/controller/readTags.js";
import { labelingProcess } from "../../../labeling/labelProcess.js";
import { autoLabelCreated } from "../../../labeling/labelRatio.js";
import { stapperFaulted, strapperFaults } from "./strapperFault.js";

export let cameraPalletCheck = 20;
export let currentPalletCheck = 0;
let lastProcessedTimestamp = 0;

export const labelerTagRead = async (tagData: any) => {
    /**
     * Reads the tag data from the Dyco PLC and processes it based on the feedback.
     */
    // Convert tag data buffer to a string and extract numeric values
    const buffer = Buffer.from(tagData.value);
    const numericString = buffer.toString("utf8").replace(/[^0-9#]/g, "");

    // Ignore empty or invalid tag data
    if (numericString === "#") {
        return;
    }

    const tagTime = new Date(tagData.state.timestamp).getTime();
    // get the settings
    const { data: settingData, error: settingError } = await tryCatch(
        db.select().from(settings)
    );

    if (settingError) {
        createLog(
            "error",
            "dyco",
            "ocp",
            "There was an error getting the settings"
        );
        return;
    }

    // check the dyco settings
    const dycoPrint = settingData.filter((n) => n.name === "dycoPrint");
    // Only process if this is a new timestamp within the last 5 seconds
    if (tagTime !== lastProcessedTimestamp && Date.now() - tagTime <= 8000) {
        lastProcessedTimestamp = tagTime;
        /**
         * add logic in to see if this is the first time we run this so we return an error to validate we are in sync.
         */
        createLog(
            "info",
            "dyco",
            "ocp",
            `Current pallet at the wrapper is: ${numericString}`
        );
        if (dycoPrint[0].value === "1") {
            createLog("info", "dyco", "ocp", "Dyco will be printing the label");
            // if (!dycoControlCheck) {
            //     createLog(
            //         "error",
            //         "dyco",
            //         "ocp",
            //         `Dyco was switch to be the printer guys. please validate the line is in sync, Current line is ${numericString}`
            //     );
            //     dycoControlCheck = true;
            //     return;
            // }

            // check the stapper error logic.

            if (stapperFaulted) {
                createLog("error", "dyco", "ocp", `Strapper is faulted.`);
                return;
            }

            // check if we need to manual check due to 20 pallets.
            if (currentPalletCheck <= cameraPalletCheck) {
                currentPalletCheck++;
                labelingProcess({ line: numericString });
                createLog(
                    "info",
                    "dyco",
                    "ocp",
                    `You have printed ${currentPalletCheck} pallets, remaining until ${
                        cameraPalletCheck - currentPalletCheck
                    }.`
                );
                autoLabelCreated();
            } else {
                currentPalletCheck = 0;
                createLog(
                    "warn",
                    "dyco",
                    "ocp",
                    `You have reached 20 pallets since the last check please validate the labeler is still in sync.`
                );
                return;
            }
        }

        if (dycoPrint[0].value === "0") {
            createLog(
                "info",
                "dyco",
                "ocp",
                "Rfid system is contorlling the printing"
            );
            // trigger the reader so we can get the label from the tag readers.
            setTimeout(async () => {
                await readTags("wrapper1");
            }, 500); // half second delay on this guy
        }
    }
};

/**
 * setting to switch between rfid and dyco labeling
 */
