@{
    ViewData["Title"] = "QR & Barcode Scanner";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div id="app" data-aos="fade-right">
    <h1 data-aos="fade-right">QR & Barcode Scanner</h1>
    <div id="reader" data-aos="fade-right"></div>
    <div v-if="qrCodeResult" id="qrCodeResult">
        <h2>Scan Result:</h2>
        <p>{{ qrCodeResult }}</p>
    </div>
</div>

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                qrCodeResult: null,
                html5QrCodeScanner: null,
                debounceTimeout: null,
            };
        },
        mounted() {
            this.startScanner();
        },
        methods: {
            startScanner() {
                const config = {
                    fps: 60,
                    qrbox: 200
                };

                navigator.mediaDevices.getUserMedia({
                    video: {
                        width: { ideal: 1920 }, // Higher resolution
                        height: { ideal: 1080 }, 
                    }
                })
                      
                    .catch((err) => {
                        console.error("Error accessing camera:", err);
                    });

                this.html5QrCodeScanner = new Html5QrcodeScanner(
                    "reader", config, false
                );

                this.html5QrCodeScanner.render(
                    (decodedText, decodedResult) => {
                        if (!this.debounceTimeout) {
                            this.debounceTimeout = setTimeout(() => {
                                this.qrCodeResult = decodedText;
                                this.sendDataToBackend(decodedText);
                                this.debounceTimeout = null;
                            }, this.debounceTime);
                        }
                    }
                );
            },
            sendDataToBackend(data) {
                fetch("/api/Qr", {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                    },
                    body: JSON.stringify({ data: data }),
                })
                    .then((response) => response.json())
                    .then((result) => {
                        console.log("Response from server:", result);
                    })
                    .catch((error) => {
                        console.error("Error sending data to the backend:", error);
                    });
            },
            decodeWithApi(barcodeData) {
                fetch(`https://api.qrserver.com/v1/read-qr-code/?fileurl=${encodeURIComponent(barcodeData)}`)
                    .then(response => response.json())
                    .then(data => {
                        console.log("Decoded using API:", data);
                        if (data[0].symbol[0].data) {
                            this.qrCodeResult = data[0].symbol[0].data; // Update result with API response
                        }
                    })
                    .catch(error => {
                        console.error("Error decoding with API:", error);
                    });
            },
            decodeWithZxing() {
                const reader = new ZXing.BrowserQRCodeReader();
                reader.decodeFromInputVideoDevice(undefined, 'reader').then(result => {
                    this.qrCodeResult = result.text;
                    this.sendDataToBackend(result.text);
                }).catch(err => {
                    console.error("ZXing decoding failed:", err);
                });
            },
        },
        beforeDestroy() {
            if (this.html5QrCodeScanner) {
                this.html5QrCodeScanner.clear();
            }
        },
    });
</script>