{% extends "base.html" %}
{% load i18n %}
{% load custom_filters %}

{% block content %}

    
<div class="container-fluid p-2">
<form id="car-form">
    <!-- Other form fields -->
    <div>
        <label for="vin_no">VIN Number:</label>
        <input type="text" id="vin_no" name="vin_no" readonly>
        <button type="button" id="scan-vin-btn">Scan VIN</button>
    </div>
    <button type="submit">Submit</button>
</form>

<!-- Scanner Modal -->
<div id="scanner-modal" style="display:none;">
    <div id="video"></div>
    <button id="stop-scanner">Stop Scanner</button>
</div>

<p id="result"></p>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/quagga/0.12.1/quagga.min.js"></script>
<script>
    const scanVinBtn = document.getElementById('scan-vin-btn');
    const vinInput = document.getElementById('vin_no');
    const scannerModal = document.getElementById('scanner-modal');
    const videoElement = document.getElementById('video');
    const stopScannerBtn = document.getElementById('stop-scanner');
    const resultElement = document.getElementById('result');

    // Open the scanner modal
    scanVinBtn.addEventListener('click', () => {
        scannerModal.style.display = 'block';
        startScanner();
    });

    // Stop the scanner
    stopScannerBtn.addEventListener('click', () => {
        stopScanner();
        scannerModal.style.display = 'none';
    });

    function startScanner() {
        Quagga.init({
            inputStream: {
                name: "Live",
                type: "LiveStream",
                target: videoElement,
            },
            decoder: {
                readers: ["code_128_reader"], // Use appropriate barcode reader
            }
        }, function(err) {
            if (err) {
                console.error(err);
                resultElement.textContent = 'Error initializing scanner.';
                return;
            }
            Quagga.start();
        });

        Quagga.onDetected(function(data) {
            const vin = data.codeResult.code;
            vinInput.value = vin; // Set the scanned VIN to the input field
            stopScanner();
            scannerModal.style.display = 'none';

            // Send the VIN via AJAX to the backend
            decodeVin(vin);
        });
    }

    function stopScanner() {
        Quagga.stop();
    }

    function decodeVin(vin) {
        fetch('/api/decode-vin/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCSRFToken()
            },
            body: JSON.stringify({ vin_no: vin })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                resultElement.textContent = `VIN decoded: ${JSON.stringify(data.data)}`;
            } else {
                resultElement.textContent = `Error: ${data.error}`;
            }
        })
        .catch(err => {
            console.error(err);
            resultElement.textContent = 'Error processing VIN.';
        });
    }

    // Function to get CSRF token
    function getCSRFToken() {
        const name = 'csrftoken';
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.startsWith(name + '=')) {
                return cookie.substring(name.length + 1);
            }
        }
        return '';
    }
</script>
{% endblock %}