const resultElement = document.getElementById("barcode-result");
const stopButton = document.getElementById("stop-button");
const productDetails = document.getElementById("product-details");
const productInfoList = document.getElementById("product-info-list");

function startScanner() {
    console.log("Starting Quagga...");
    Quagga.init({
        inputStream: {
            name: "Live",
            type: "LiveStream",
            target: document.querySelector("#video-preview"),
        },
        decoder: {
            readers: ["ean_reader", "code_128_reader", "upc_reader"],
        },
    }, function(err) {
        if (err) {
            console.error("Ошибка инициализации Quagga:", err);
            alert("Ошибка инициализации камеры");
            return;
        }
        console.log("Quagga started successfully.");
        Quagga.start();
        stopButton.style.display = "inline";
    });

    Quagga.onDetected(function(data) {
        const barcode = data.codeResult.code;
        resultElement.innerText = barcode;
        Quagga.stop();
        stopButton.style.display = "none";

        fetch('/warehouse/process-barcode/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ barcode: barcode })
        })
        .then(response => response.json())
        .then(product => {
            if (product.error) {
                alert(product.error);
                return;
            }
            productInfoList.innerHTML = '';
            for (const [key, value] of Object.entries(product)) {
                const listItem = document.createElement('li');
                listItem.innerText = `${key}: ${value}`;
                productInfoList.appendChild(listItem);
            }
            productDetails.style.display = "block";
        })
        .catch(error => {
            console.error("Ошибка:", error);
            alert("Ошибка на сервере или продукт не найден.");
        });
    });
}

stopButton.addEventListener("click", () => {
    Quagga.stop();
    stopButton.style.display = "none";
});

document.addEventListener("DOMContentLoaded", startScanner);
