//http://usday1vms006:4000/api/v1/zebra/wrapper1
import { z, createRoute, OpenAPIHono } from "@hono/zod-openapi";
import { ConsoleLogWriter } from "drizzle-orm";
import { tagData } from "../controller/tagData.js";
import { responses } from "../../../globalUtils/routeDefs/responses.js";
import { clearNoReadTimer, noRead } from "../controller/noRead.js";
import { badRead, goodRead } from "../controller/readerControl.js";
import { createLog } from "../../logger/logger.js";
import { tryCatch } from "../../../globalUtils/tryCatch.js";
import { stopRead } from "../controller/readTags.js";
import { apiHit } from "../../../globalUtils/apiHits.js";

const app = new OpenAPIHono();

const ParamsSchema = z.object({
    reader: z
        .string()
        .min(3)
        .openapi({
            param: {
                name: "reader",
                in: "path",
            },
            example: "1212121",
        }),
});

app.openapi(
    createRoute({
        tags: ["rfid"],
        summary: "Tag info posted from the reader.",
        method: "post",
        path: "/taginfo/{reader}",
        request: {
            params: ParamsSchema,
        },
        responses: responses(),
    }),
    async (c) => {
        const { reader } = c.req.valid("param");
        createLog("info", "rfid", "rfid", `${reader} is sending us data.`);
        let tagdata: any = [];
        const { data: body, error: bodyError } = await tryCatch(c.req.json());
        apiHit(c, { endpoint: `/taginfo/${reader}`, lastBody: body });
        if (bodyError) {
            return c.json({ success: false, message: "missing data" }, 400);
        }
        //console.log(`Tag: ${Buffer.from(body.idHex, "hex").toString("utf-8")}, ${body[key].data.idHex}`);

        for (let i = 0; i < body.length; i++) {
            const tag = Buffer.from(body[i].data.idHex, "hex").toString(
                "utf-8"
            );
            // console.log(
            //     "Raw value:",
            //     body[i].data.peakRssi,
            //     "Parsed:",
            //     parseInt(body[i].data.peakRssi)
            // );
            if (
                tag.includes("ALPLA") &&
                parseInt(body[i].data.peakRssi) < -30
            ) {
                tagdata = [
                    ...tagdata,
                    {
                        tagHex: body[i].data.idHex,
                        reader: reader,
                        tag: tag,
                        timeStamp: body[i].timestamp,
                        antenna: body[i].data.antenna,
                        tagStrength: body[i].data.peakRssi,
                    },
                ];
            }
        }

        if (tagdata.length === 0) {
            // noRead(reader);
            // badRead(reader);
            return c.json(
                { success: false, message: `There were no tags scanned.` },
                200
            );
        } else {
            tagData(tagdata);
            goodRead(reader);
            clearNoReadTimer();

            return c.json(
                { success: true, message: `New info from ${reader}` },
                200
            );
        }
    }
);

export default app;
