import axios from "axios";
import { createLog } from "../../logger/logger.js";
import { db } from "../../../../database/dbclient.js";
import { rfidReaders } from "../../../../database/schema/rfidReaders.js";
import { eq } from "drizzle-orm";
import { noRead, startNoReadTimer } from "./noRead.js";
import { badRead } from "./readerControl.js";

const authData = btoa("admin:Zebra123!");
let token: string;
let ip: string;
export const readTags = async (reader: string) => {
    /**
     * Start the read for x seconds then auto stop it
     */
    createLog("info", "rfid", "rfid", `Read was just triggered from ${reader}`);
    const readers = await db
        .select()
        .from(rfidReaders)
        .where(eq(rfidReaders.active, true));
    if (readers.length === 0) {
        createLog(
            "error",
            "rfid",
            "rfid",
            `There are no active readers right now maybe one forgot to be activated`
        );
        return;
    }
    // get the auth token
    ip = readers.find((r) => r.reader === reader)?.readerIP as string;

    // start the read
    startRead(reader, ip);

    // start the read
};
const getReaderToken = async () => {
    try {
        const res = await axios.get(`https://${ip}/cloud/localRestLogin`, {
            headers: { Authorization: `Basic ${authData}` },
        });
        token = res.data.message;
    } catch (error: any) {
        createLog(
            "error",
            "rfid",
            "rfid",
            `There was an error Getting the token the read: ${error.response?.data.message}`
        );
    }
};

const startRead = async (reader: string, ip: string) => {
    await getReaderToken();
    try {
        const res = await axios.put(
            `https://${ip}/cloud/start`,
            {},
            {
                headers: { Authorization: `Bearer ${token}` },
            }
        );

        //console.log(res.data);

        if (res.status === 200) {
            // start the no read timer
            startNoReadTimer(() => {
                noRead(reader);
                badRead(reader);
            });
            setTimeout(() => {
                stopRead(reader, ip);
            }, 5 * 1000);
        }

        // stop after 5 seconds
    } catch (error: any) {
        if (error.response?.data.code === 3) {
            stopRead(reader, ip);
            setTimeout(() => {
                startRead(reader, ip);
            }, 2 * 1000);
        }
        createLog(
            "error",
            "rfid",
            "rfid",
            `There was an error Starting the read: ${error.response?.data.message}`
        );
    }
};

export const stopRead = async (reader: string, ip: string) => {
    await getReaderToken();
    try {
        const res = await axios.put(
            `https://${ip}/cloud/stop`,
            {},
            {
                headers: { Authorization: `Bearer ${token}` },
            }
        );
    } catch (error: any) {
        createLog(
            "error",
            "rfid",
            "rfid",
            `There was an error Stopping the read on ${reader}`
        );
    }
};
