<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add New Book - LiteLib</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    <link rel="stylesheet" href="/css/style.css">

    <!-- Favicon Information -->
    <link rel="apple-touch-icon" sizes="180x180" href="/favicon/apple-touch-icon.png">
    <link rel="icon" type="image/png" sizes="32x32" href="/favicon/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="194x194" href="/favicon/favicon-194x194.png">
    <link rel="icon" type="image/png" sizes="192x192" href="/favicon/android-chrome-192x192.png">
    <link rel="icon" type="image/png" sizes="16x16" href="/favicon/favicon-16x16.png">
    <link rel="manifest" href="/favicon/site.webmanifest">
    <link rel="mask-icon" href="/favicon/safari-pinned-tab.svg" color="#805a3f">
    <link rel="shortcut icon" href="/favicon/favicon.ico">
    <meta name="msapplication-TileColor" content="#ffffff">
    <meta name="msapplication-TileImage" content="/favicon/mstile-144x144.png">
    <meta name="msapplication-config" content="/favicon/browserconfig.xml">
    <meta name="theme-color" content="#ffffff">
</head>
<body>

<audio src="/sounds/success.mp3" id="success" autostart="false" class="hide"></audio>
<audio src="/sounds/error.mp3" id="error" autostart="false" class="hide"></audio>

<div class="container mt-5">
    <h1 class="mt-5 mb-5" style="text-align:center;"><i class="bi bi-plus-square"></i> Adding New Book</h1>
    <div id="alert"></div>
</div>

<div id="barcode-scanner" class="container"></div>
<br>
<div class="container" id="formFields">
    <form action="/add-book" method="post" id="userForm">
        <label for="name" style="text-align: left;">Book Title:</label>
        <input id="name" name="name" class="form-control form-control-lg mb-5" value="" required>
        <label for="author" style="text-align: left;">Author:</label>
        <input id="author" name="author" class="form-control form-control-lg mb-5" value="" required>

        <div class="row">
            <div class="col">
                <label for="year" style="text-align: left;">Year:</label>
                <input id="year" name="year" class="form-control form-control-lg mb-5" value="" type="number">
            </div>
            <div class="col">
                <label for="genre" style="text-align: left;">Genre:</label>
                <input id="genre" name="genre" class="form-control form-control-lg mb-5" type="text" autocomplete="genre">
            </div>
        </div>

        <div class="row">
            <div class="col">
                <label for="ISBN" style="text-align: left;">ISBN:</label>
                <input id="ISBN" name="ISBN" class="form-control form-control-lg mb-5" value="">
            </div>
            <div class="col">
                <label for="ISBN10" style="text-align: left;">ISBN10:</label>
                <input id="ISBN10" name="ISBN10" class="form-control form-control-lg mb-5" value="">
            </div>
        </div>

        <label for="copies" style="text-align: left;">Copies:</label>
        <input id="copies" name="copies" class="form-control form-control-lg mb-5" value="1" type="number" min="1" autocomplete="copies" required>

        <!-- Buttons -->
        <div class="container" style="padding: 0px;">
            <div class="d-flex justify-content-between align-items-center">
              <a href="/" class="btn btn-primary btn-lg"><i class="bi bi-house-door-fill"></i> Home</a>
              <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                <a href="/books" class="btn btn-secondary btn-lg"><i class="bi bi-x-circle-fill"></i> Cancel</a>
                <button type="submit" class="btn btn-primary btn-lg"><i class="bi bi-floppy2-fill"></i> Save</button>
              </div>
            </div>
        </div>

    </form>
</div>

<!-- Include the QuaggaJS library -->
<script src="https://cdn.jsdelivr.net/npm/quagga/dist/quagga.min.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Configure QuaggaJS
        Quagga.init({
            inputStream : {
                name : "Live",
                type : "LiveStream",
                target: document.querySelector('#barcode-scanner')
            },
            decoder : {
                readers : ["ean_reader"]
            }
        }, function(err) {
            if (err) {
                console.error("Quagga initialization failed: ", err);
                return;
            }
            console.log("Initialization finished. Ready to start");
            Quagga.start();
        });

        // Add event listener for barcode detection
        Quagga.onDetected(function(result) {
            // removeBootstrapAlert();
            var code = result.codeResult.code;
            fetchBookDetails(code);
        });

        // Function to fetch book details from the API
        function fetchBookDetails(isbn) {
            var apiUrl = 'https://openlibrary.org/api/books?bibkeys=ISBN:' + isbn + '&jscmd=details&format=json';
            fetch(apiUrl)
                .then(response => response.json())
                .then(data => {
                    if (Object.keys(data).length == 0) {
                        bootstrapAlert("Book details not found on openlibrary.org", "danger");
                        playSound('error');
                        throw new Error('Book details not found');
                    }
                    var bookDetails = data['ISBN:' + isbn].details;
                    if (!bookDetails) {
                        bootstrapAlert("Book details not found on openlibrary.org", "danger");
                        playSound('error');
                        throw new Error('Book details not found');
                    }
                    removeBootstrapAlert();
                    
                    var title = bookDetails.title || '';
                    var author = bookDetails.authors ? bookDetails.authors[0].name : '';
                    var publishDate = bookDetails.publish_date || '';
                    var genre = ''; // Need to update this to retrieve genre from API
                    var isbn10 = bookDetails.isbn_10 ? bookDetails.isbn_10[0] : '';
                    var year = bookDetails.publish_date ? parseInt(bookDetails.publish_date.match(/\d{4}/)[0]) : '';

                    // Fill the form fields with retrieved book details
                    document.getElementById('name').value = title;
                    document.getElementById('author').value = author;
                    document.getElementById('genre').value = genre;
                    document.getElementById('ISBN').value = isbn;
                    document.getElementById('ISBN10').value = isbn10;
                    document.getElementById('year').value = year; // Set the year field to the published date
                    // document.getElementById("formFields").scrollIntoView();
                    playSound('success');
                })
                .catch(error => {
                    console.error('Error fetching book details:', error);
                });
        }
    });

    function playSound(soundname) {
        const thissound = document.getElementById(soundname);
        thissound.play();
    }

    function bootstrapAlert(message, type) {
        const existingAlert = document.querySelector('.alert.alert-' + type);
        // Alert with the same message already exists, no need to create a new one
        if (existingAlert) return;

        const alert = document.createElement('div');
        alert.classList.add('alert', 'alert-' + type);
        alert.textContent = message;
        document.getElementById('alert').appendChild(alert);
    }

    function removeBootstrapAlert() {
        var alertElement = document.getElementById('alert');
        while (alertElement.firstChild) {
            alertElement.removeChild(alertElement.firstChild);
        }
    }
</script>

</body>
</html>
