{% include 'header.html' %}

<body>
<header>
    <nav class="container">
        <ul>
            <li><a href="/">Chatbot</a></li>
            <li><a href="/tts">TTS</a></li>
            {% include 'le_funny_dropdown.html' %}
        </ul>
        {% include 'logout.html' %}
    </nav>
    <script>
        function timestampToAwareDatetime(timestamp) {
            const awareDatetime = new Date(timestamp);
            awareDatetime.setMinutes(awareDatetime.getMinutes() - awareDatetime.getTimezoneOffset());
            return awareDatetime;
        }

        function prettifyTimestamp(timestamp) {
            const awareDatetime = timestampToAwareDatetime(timestamp);
            return awareDatetime.toLocaleString();
        }

        function saveNewSentence(shortHash) {
            /*
            Save a newly-added sentence by POST'ing against /api/v1/sentences.

            - if response is not 200, return nothing (validation logic to be added later
            - if response is 200, retrieve save-new-${shortHash} and delete-new-${shortHas} and change their ids
            to save-${newSentenceIdRetrievedFromResponse} and delete-${newSentenceIdRetrievedFromResponse}
            assume a body like: {"id": 1, "sentence": "New sentence"}

             */
            const sentenceTextInput = document.getElementById(`newSentence${shortHash}`);
            const sentence = sentenceTextInput.value;
            // if sentence is empty, return
            if (!sentence) {
                return;
            }
            const sentenceData = {
                "sentence": sentence
            }
            fetch(`/api/v1/sentences`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(sentenceData)
            }).then(response => {
                response.json().then(data => {
                    console.log(data);
                    const saveButton = document.getElementById(`saveNew${shortHash}`);
                    const deleteButton = document.getElementById(`deleteNew${shortHash}`);
                    saveButton.id = `save-${data.id}`;
                    deleteButton.id = `delete-${data.id}`;
                });
            });

        }

        function saveExistingSentence(id) {
            // get sentence value by
        }

        document.addEventListener('DOMContentLoaded', function () {
            const timestampCells = document.querySelectorAll('.timestamp-cell');
            console.log(timestampCells);
            timestampCells.forEach(cell => {
                const timestampStr = cell.textContent.trim();
                const timestamp = parseFloat(timestampStr) * 1000;
                cell.textContent = prettifyTimestamp(timestamp);
            });

            const addButton = document.getElementById('add-sentence');
            addButton.addEventListener('click', () => {
                // add a new empty row at the top of the tbody
                const sentencesTable = document.getElementById('sentencesTable');
                const newRow = sentencesTable.insertRow();
                const nowPrettyDate = prettifyTimestamp(Date.now());
                const shortHash = Math.random().toString(36).substring(2, 10);
                newRow.innerHTML = `
                <td><textarea placeholder="Enter new sentence" id="newSentence${shortHash}"></textarea></td>
                    <td class="timestamp-cell">${nowPrettyDate}</td>
                    <td>
                        <div class="container">
                            <button id="saveNew${shortHash}" style="background-color: #00c482; border-color: #00c482" onclick="saveNewSentence('${shortHash}')">
                                Save
                            </button>
                            <button id="deleteNew${shortHash}" style="border-color: #aa0000; background-color: #aa0000" onclick="this.parentElement.parentElement.parentElement.remove()">
                                Delete
                            </button>
                        </div>
                    </td>
                `;
            });
        });
    </script>
</header>
<main class="container">
    <section>
        <form role="search">
            <input name="search" type="search" placeholder="Search sentence"/>
            <input type="submit" value="Search"/>
            <button id="add-sentence" class="secondary" type="button">Add</button>
        </form>
        <table id="sentencesTable">
            <thead style="background-color: white; color: black">
            <tr>
                <th scope="col">Sentence</th>
                <th scope="col">Last modified</th>
                <th scope="col">Action</th>
            </tr>
            </thead>
            <tbody id="sentencesTableBody">
            {% for sentence in sentences %}
            <tr>
                <td><textarea>{{ sentence.sentence }}</textarea></td>
                <td class="timestamp-cell">{{ sentence.last_updated_at }}</td>
                <td>
                    <div class="container">
                        <button id="save-{{ sentence.id }}" style="background-color: #00c482; border-color: #00c482">
                            Save
                        </button>
                        <button id="delete-{{ sentence.id }}" style="border-color: #aa0000; background-color: #aa0000">
                            Delete
                        </button>
                    </div>
                </td>
            </tr>
            {% endfor %}
            </tbody>
        </table>
    </section>
</main>
</body>
</html>
