<!DOCTYPE html>
<!--
 Copyright 2025 Dimensional Inc.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Video Stream Example</title>
    <style>
        body {
            margin: 0;
            padding: 20px;
            font-family: Arial, sans-serif;
            background-color: #f0f0f0;
        }

        h1 {
            text-align: center;
            margin-bottom: 30px;
            color: #333;
        }

        .stream-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
            gap: 20px;
            padding: 20px;
            max-width: 1800px;
            margin: 0 auto;
        }

        .stream-container {
            background: white;
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .stream-container h2 {
            text-align: center;
            margin: 0 0 15px 0;
            color: #444;
            font-size: 1.2em;
        }

        .stream-container img {
            width: 100%;
            height: auto;
            display: block;
            border-radius: 4px;
        }

        .button-container {
            display: flex;
            justify-content: center;
            gap: 10px;
            margin-top: 15px;
        }

        button {
            padding: 8px 20px;
            font-size: 14px;
            cursor: pointer;
            background-color: #007BFF;
            color: white;
            border: none;
            border-radius: 5px;
            transition: background-color 0.3s;
        }

        button:hover {
            background-color: #0056b3;
        }

        #reload-button {
            display: block;
            width: 200px;
            margin: 20px auto;
            padding: 10px;
            font-size: 16px;
            cursor: pointer;
            background-color: #007BFF;
            color: white;
            border: none;
            border-radius: 5px;
            transition: background-color 0.3s;
        }

        #reload-button:hover {
            background-color: #0056b3;
        }

        /* Responsive adjustments */
        @media (max-width: 900px) {
            .stream-grid {
                grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            }
        }

        @media (max-width: 600px) {
            .stream-grid {
                grid-template-columns: 1fr;
            }
        }

        .query-container {
            max-width: 800px;
            margin: 30px auto;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .query-form {
            display: flex;
            gap: 10px;
        }

        .query-input {
            flex-grow: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 16px;
        }

        .query-button {
            padding: 10px 20px;
            background-color: #28a745;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s;
        }

        .query-button:hover {
            background-color: #218838;
        }

        .query-response {
            margin-top: 15px;
            padding: 10px;
            border-radius: 5px;
            display: none;
        }

        .success {
            background-color: #d4edda;
            color: #155724;
        }

        .error {
            background-color: #f8d7da;
            color: #721c24;
        }

        .text-streams-container {
            max-width: 800px;
            margin: 30px auto;
        }

        .text-stream-container {
            background: white;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .text-stream-container h3 {
            margin-top: 0;
            color: #444;
        }

        .text-messages {
            height: 200px;
            overflow-y: auto;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            margin-bottom: 10px;
            background-color: #f9f9f9;
        }

        .text-message {
            padding: 8px;
            margin-bottom: 8px;
            background-color: white;
            border-radius: 4px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
    </style>
</head>
<body>
    <h1>Live Video Streams</h1>

    <div class="query-container">
        <h2>Ask a Question</h2>
        <form id="queryForm" class="query-form">
            <input type="text" id="queryInput" class="query-input" placeholder="Type your query here..." required>
            <button type="submit" class="query-button">Send</button>
        </form>
        <div id="queryResponse" class="query-response"></div>
    </div>

    <!-- Add text streams section -->
    {% if text_stream_keys %}
    <div class="text-streams-container">
        <h2>Text Streams</h2>
        {% for key in text_stream_keys %}
            <div class="text-stream-container" id="text_container_{{ key }}">
                <h3>{{ key.replace('_', ' ').title() }}</h3>
                <div class="text-messages" id="text_messages_{{ key }}"></div>
                <div class="button-container">
                    <button onclick="connectTextStream('{{ key }}')">Connect</button>
                    <button onclick="disconnectTextStream('{{ key }}')">Disconnect</button>
                    <button onclick="clearTextStream('{{ key }}')">Clear</button>
                </div>
            </div>
        {% endfor %}
    </div>
    {% endif %}

    <div class="stream-grid">
        {% for key in stream_keys %}
            <div class="stream-container">
                <h2>{{ key.replace('_', ' ').title() }}</h2>
                <img id="img_{{ key }}" src="" alt="{{ key }} Feed">
                <div class="button-container">
                    <button onclick="startStream('{{ key }}')">Start</button>
                    <button onclick="stopStream('{{ key }}')">Stop</button>
                </div>
            </div>
        {% endfor %}
    </div>

    <button id="reload-button" onclick="reloadPage()">Reload Page</button>

    <script>
        // Start all streams when the page loads
        window.onload = function() {
            {% for key in stream_keys %}
                startStream('{{ key }}');
            {% endfor %}
        }

        function startStream(key) {
            const img = document.getElementById('img_' + key);
            img.src = "/video_feed/" + key;
        }

        function stopStream(key) {
            const img = document.getElementById('img_' + key);
            img.src = "";
        }

        function reloadPage() {
            window.location.reload(true);
        }

        // Handle query form submission
        document.getElementById('queryForm').addEventListener('submit', async function(e) {
            e.preventDefault();

            const queryInput = document.getElementById('queryInput');
            const queryResponse = document.getElementById('queryResponse');
            const query = queryInput.value.trim();

            if (!query) return;

            try {
                const formData = new FormData();
                formData.append('query', query);

                const response = await fetch('/submit_query', {
                    method: 'POST',
                    body: formData
                });

                let result;

                // Better error handling for non-200 responses
                if (!response.ok) {
                    try {
                        // Try to parse as JSON first
                        result = await response.json();
                    } catch (jsonError) {
                        // If not JSON, get text and create a result object
                        const errorText = await response.text();
                        result = {
                            success: false,
                            message: `Server error: ${response.status} ${response.statusText}`,
                            details: errorText.substring(0, 100) // Just the first part to avoid showing too much HTML
                        };
                    }
                } else {
                    result = await response.json();
                }

                queryResponse.textContent = result.message;
                queryResponse.className = 'query-response ' + (result.success ? 'success' : 'error');
                queryResponse.style.display = 'block';

                if (result.success) {
                    queryInput.value = '';

                    // Hide the success message after 3 seconds
                    setTimeout(() => {
                        queryResponse.style.display = 'none';
                    }, 3000);
                }
            } catch (error) {
                queryResponse.textContent = 'Error sending query: ' + error.message;
                queryResponse.className = 'query-response error';
                queryResponse.style.display = 'block';
            }
        });

        // Text stream event sources
        const textEventSources = {};

        function connectTextStream(key) {
            // Close if already open
            if (textEventSources[key]) {
                textEventSources[key].close();
            }

            // Connect to the server-sent events endpoint
            const eventSource = new EventSource(`/text_stream/${key}`);
            textEventSources[key] = eventSource;

            // Handle incoming messages
            eventSource.addEventListener('message', function(event) {
                const messagesContainer = document.getElementById(`text_messages_${key}`);
                const messageElement = document.createElement('div');
                messageElement.className = 'text-message';
                messageElement.textContent = event.data;
                messagesContainer.appendChild(messageElement);

                // Scroll to the bottom to show latest message
                messagesContainer.scrollTop = messagesContainer.scrollHeight;
            });

            // Handle connection errors
            eventSource.onerror = function() {
                console.error(`Error in text stream ${key}`);
                eventSource.close();
                delete textEventSources[key];
            };
        }

        function disconnectTextStream(key) {
            if (textEventSources[key]) {
                textEventSources[key].close();
                delete textEventSources[key];
            }
        }

        function clearTextStream(key) {
            const messagesContainer = document.getElementById(`text_messages_${key}`);
            messagesContainer.innerHTML = '';
        }

        // Auto-connect text streams on page load
        window.addEventListener('load', function() {
            {% for key in text_stream_keys %}
                connectTextStream('{{ key }}');
            {% endfor %}
        });
    </script>
</body>
</html>
