import { useState } from "react";
import { useWindowEvent } from "@mantine/hooks";

const useScanning = () => {
    const [scanningValue, setScanningValue] = useState<string>("");
    const [scannedValue, setScannedValue] = useState<string>("");
    const [isScanning, setIsScanning] = useState<boolean>(false);

    const setIsScanningValue = (isScanning: boolean) => {
        if (!isScanning) {
            setScanningValue("");
        }
        setIsScanning(isScanning);
    };

    useWindowEvent("keydown", (event) => {
        if (!isScanning) return;
        event.preventDefault();
        setScanningValue(prevState => prevState + event.key);
        if (["\n", "\r", "Enter"].includes(event.key)) {
            setScannedValue(scanningValue);
            setIsScanningValue(false);
        }
    });

    return {
        isScanning,
        setIsScanning: setIsScanningValue,
        scannedValue,
        setScannedValue,
    };
};

export default useScanning;
