{% include 'header.html' %}

<body>
<header>
    <nav class="container">
        <ul>
            <li>Chatbot</li>
            <li><a href="/tts" disabled>TTS</a></li>
            {% include 'le_funny_dropdown.html' %}
        </ul>
        {% include 'logout.html' %}
    </nav>
</header>
<main class="container">
    <section>
        <form>
            <label for="channelName">Enter channel name:</label>
            <input type="text" id="channelName" placeholder="huesoperro" aria-describedby="channelNameValidHelper">
            <small id="channelNameValidHelper"></small>
            <button id="startButton" type="button">Start chatbot</button>
            <button id="stopButton" type="button" disabled style="background-color: #aa0000; border-color: #aa0000">Stop
                chatbot
            </button>
            <br/>

        </form>
        <details>
            <summary>Chatbot settings</summary>
            <form>
                <label for="automaticGenerationTimer">Automatic generation timer (seconds)</label>
                <input type="number" id="automaticGenerationTimer" placeholder="300"
                       value="{{ automatic_generation_timer }}">

                <label for="automaticQuotesTimer">Automatic quotes timer (seconds)</label>
                <input type="number" id="automaticQuotesTimer" placeholder="500" value="{{ automatic_quote_timer }}">

                <label for="mods">Chatbot mods (comma-separated)</label>
                <input type="text" id="mods" placeholder="huesoporro" value="{{ ','.join(mods) or '' }}">

                <button id="saveSettings" type="button" style="background-color: #00c482; border-color: #00c482">
                    Save settings
                </button>
            </form>
        </details>
    </section>
</main>
<script>
    document.addEventListener("DOMContentLoaded", () => {
        class ChatbotManager {

            constructor() {
                this.stopButton = document.getElementById("stopButton");
                this.startButton = document.getElementById("startButton");
                this.automaticGenerationTimerInput = document.getElementById("automaticGenerationTimer");
                this.automaticQuotesTimerInput = document.getElementById("automaticQuotesTimer");
                this.modsInput = document.getElementById("mods");
                this.channelNameInput = document.getElementById("channelName");

            }

            setEvents() {
                document.getElementById('saveSettings').addEventListener('click', () => {
                    chatbotManager.saveBotSettings()
                })


                this.startButton.addEventListener('click', () => {
                    const channelName = this.channelNameInput ? this.channelNameInput.value : '';
                    if (!channelName) {
                        document.getElementById('channelNameValidHelper').textContent = 'Please enter a channel name';
                        this.channelNameInput.setAttribute('aria-invalid', 'true');
                        return;
                    }

                    document.getElementById('channelNameValidHelper').textContent = 'Looks good!';
                    this.channelNameInput.setAttribute('aria-invalid', 'false');

                    this.startBot()
                        .then(() => {
                            console.log('Chatbot started successfully');
                        })
                        .catch((error) => {
                            console.error('Failed to start chatbot', error);
                        });
                });

                this.stopButton.addEventListener('click', () => {
                    chatbotManager.stopBot()
                        .then(() => {
                            console.log('Chatbot stopped successfully');
                        })
                        .catch((error) => {
                            console.error('Failed to stop chatbot', error);
                        });
                });

                setInterval(() => {
                    this.getBotStatus()
                        .then(() => {
                            console.log('Chatbot status retrieved successfully');
                        })
                        .catch((error) => {
                            console.error('Failed to retrieve chatbot status', error);
                        });
                }, 5000);
            }

            async startBot() {
                // call PUT /bot/start with the channel name as a query param
                const channelNameInput = document.getElementById('channelName');
                const channelName = channelNameInput ? channelNameInput.value : '';
                const response = await fetch(`/api/v1/bot`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        "command": "start",
                        "channel_name": channelName
                    })
                });
                const data = await response.json();
                console.log(data);
            }

            async stopBot() {
                // call PUT /bot/stop
                const response = await fetch(`/api/v1/bot`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        "command": "stop",
                    }),
                });
                const data = await response.json();
                console.log(data);
                // disable startButton
                startButton.disabled = true;
                stopButton.disabled = false;
            }

            setButtonsStatus(status) {
                this.startButton.disabled = status === "ok";
                this.stopButton.disabled = status === "ko";
            }

            async getBotStatus() {
                const response = await fetch(`/api/v1/bot`, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                });
                const data = await response.json();
                console.log(data);

                this.setButtonsStatus(data.status)
            }

            async saveBotSettings() {
                const automatic_generation_timer = this.automaticGenerationTimerInput.value
                const automatic_quote_timer = this.automaticQuotesTimerInput.value
                const mods = this.modsInput.value.split(",")
                const response = await fetch(`/api/v1/bot/settings`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        'automatic_generation_timer': automatic_generation_timer,
                        "automatic_quote_timer": automatic_quote_timer,
                        "mods": mods,
                    })
                })
                const data = await response.json()
                console.log(data);
                if (response.ok) {
                    alert("Settings saved successfully")
                }
            }
        }

        const chatbotManager = new ChatbotManager();
        chatbotManager.setEvents();

    });
</script>
</body>

</html>
