<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat Interface</title>

    <script src="https://cdn.socket.io/4.5.4/socket.io.min.js"></script>
    <script>
        // Global constants
        const socket = io("http://127.0.0.1:5000");     // TODO: Change this
        const stream_id = "{{ stream_id }}";
        const chatter_id = "{{ chatter_id }}";
        
        function add_to_chat(data){
            const chat_container = document.getElementById("chat_container");
            console.log(data)

            // Add each chat message to the chat box, one by one
            data.forEach((element) => {
                const div = document.createElement("div");
                div.textContent = `${element.time_sent} ${element.chatter_id}: ${element.message}`;
                chat_container.appendChild(div);
            })
            
            chat_container.scrollTop = chat_container.scrollHeight; // keeps you at the bottom of the chat
        }

        socket.on("connect", () => {
            console.log("Socket Connection established!");
        })

        // Wait for a new message to be sent
        socket.on("new_message", (data) => {
            console.log("New message");
            add_to_chat([data]);
        });

        function loadPrevChat() {
            const init_chat_logs = JSON.parse('{{ chat_history | tojson }}');
            add_to_chat(init_chat_logs);
            
        }

        function sendChat(){
            // Get the chat message sent by user, if none, don't
            const chat_message = document.getElementById("messageInput").value.trim();
            if (!chat_message) return;

            document.getElementById("messageInput").value = ""; // clear the chat box

            // Send the message using sockets
            socket.emit("send_message", {
                chatter_id: chatter_id,
                stream_id: stream_id,
                message: chat_message
            });

        }

        window.addEventListener('DOMContentLoaded', () => {
            socket.emit("join", {stream_id: stream_id});
            loadPrevChat();
        });

        window.addEventListener("beforeunload", () => {
            socket.emit("leave", {stream_id: stream_id});
        });

    </script>

</head>
<body>
    <h1>Chat for Stream #{{ stream_id }}</h1>
    <div id="chat_container" style="max-height: 400px; overflow-y: auto;"></div>
    <input type="text" id="messageInput" placeholder="Type a message" />
    <button onclick="sendChat()">Send</button>
</body>
</html>
