%%

<!DOCTYPE html>
<html>
<head>
    <title>Book Log</title>
    <script src="main.js"></script>
</head>
<body>
    <h1>Book Log</h1>
    <form id="bookForm">
        <label for="username">Username:</label>
        <input type="text" id="username" required><br>
        <label for="name">Name:</label>
        <input type="text" id="name" required><br>
        <label for="book">Book:</label>
        <input type="text" id="book" required><br>
        <label for="finishedate">Finished Date:</label>
        <input type="text" id="finishedate" required><br>
        <label for="rating">Rating:</label>
        <input type="number" id="rating" min="1" max="5" required><br>
        <button type="submit">Submit</button>
    </form>
    <div id="bookList"></div>
</body>
</html>


document.addEventListener("DOMContentLoaded", function() {
    fetchBooks();
    document.getElementById("bookForm").addEventListener("submit", addBook);
});

function fetchBooks() {
    fetch("/api/readers")
        .then(response => response.json())
        .then(data => displayBooks(data))
        .catch(error => console.log(error));
}

function displayBooks(books) {
    const bookList = document.getElementById("bookList");
    bookList.innerHTML = "";

    books.forEach(book => {
        const bookItem = document.createElement("div");
        bookItem.classList.add("book-item");

        const bookInfo = document.createElement("p");
        bookInfo.innerHTML = `<strong>${book.username}</strong> read <em>${book.book}</em> and gave it a rating of ${book.rating}.`;

        bookItem.appendChild(bookInfo);
        bookList.appendChild(bookItem);
    });
}

function addBook(event) {
    event.preventDefault();

    const username = document.getElementById("username").value;
    const name = document.getElementById("name").value;
    const book = document.getElementById("book").value;
    const finishedate = document.getElementById("finishedate").value;
    const rating = document.getElementById("rating").value;

    const bookData = {
        username: username,
        name: name,
        book: book,
        finishedate: finishedate,
        rating: rating
    };

    fetch("/api/readers", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(bookData)
    })
    .then(response => response.json())
    .then(data => {
        console.log(data);
        fetchBooks();
        document.getElementById("bookForm").reset();
    })
    .catch(error => console.log(error));
}