<!--

    Queue - A Queueing system that can be used to handle labs in higher education
    Copyright (C) 2016-2024  Delft University of Technology

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

-->
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{edition/view}">
    <!--@thymesVar id="edition" type="nl.tudelft.labracore.api.dto.EditionDetailsDTO"-->

    <!--@thymesVar id="role" type="nl.tudelft.queue.dto.create.QueueRoleCreateDTO"-->

    <!--@thymesVar id="csvError" type="java.lang.String"-->
    <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.32.0/codemirror.min.js"></script>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.32.0/codemirror.min.css" />
    </head>

    <body>
        <section class="flex vertical" layout:fragment="subcontent">
            <div class="banner mb-3" data-type="error" th:if="${error != null}">
                <p th:text="${error}"></p>
            </div>
            <div>
                <h3 class="font-500 mb-3">Add single participant</h3>
                <form
                    action="#"
                    th:object="${role}"
                    th:action="@{/edition/{editionId}/participants/create(editionId=${edition.id})}"
                    class="flex vertical"
                    method="post"
                    id="createParticipantForm">
                    <input type="hidden" th:field="*{editionId}" />
                    <div class="grid col-2 gap-3 align-center" style="--col-1: minmax(0, 8rem)">
                        <label for="inputRole">Select role</label>
                        <div>
                            <select class="textfield" id="inputRole" th:field="*{type}" data-select required>
                                <option value="STUDENT">Student</option>
                                <option value="TA">TA</option>
                                <option value="HEAD_TA">Head TA</option>
                                <option value="TEACHER" th:if="${@permissionService.canManageTeachers(edition.id)}">Teacher</option>
                            </select>
                        </div>

                        <label for="inputIdentifier">Identifier</label>
                        <div>
                            <div>
                                <input
                                    type="text"
                                    th:classappend="${#fields.hasErrors('identifier')} ? 'is-invalid'"
                                    id="inputIdentifier"
                                    class="textfield"
                                    th:oninput="handleInput()"
                                    placeholder="NetId/Name/Email/#"
                                    th:field="*{identifier}" />
                            </div>
                        </div>
                    </div>

                    <div id="peopleTable" th:replace="~{edition/view/people-search}"></div>
                </form>
            </div>

            <div class="underlined"></div>

            <div th:if="${@permissionService.canManageTeachers(edition.id)}">
                <h3 class="font-500 mb-3">Import participants</h3>
                <p class="mb-5">You can upload a CSV with NetIDs and their roles</p>

                <form
                    action="#"
                    th:action="@{/edition/{editionId}/participants/import(editionId=${edition.id})}"
                    enctype="multipart/form-data"
                    class="flex vertical"
                    method="post">
                    <div class="grid align-center gap-3 col-2" style="--col-1: minmax(0, 8rem)">
                        <label for="csv" class="csvfile">CSV file</label>
                        <input type="file" id="csv" name="file" class="csvfile" />
                    </div>

                    <div>
                        The CSV should look like:
                        <br />
                        <div id="csvExample"></div>
                        The following roles can be applied:
                        <i>STUDENT, TA, HEAD_TA, TEACHER and TEACHER_RO</i>
                    </div>

                    <script>
                        $(function () {
                            let csvExample = CodeMirror(document.getElementById("csvExample"), {
                                value: ' "name", "role" \n "netid1","role1" \n "netid2","role2"',
                                mode: "mathematica",
                                lineNumbers: true,
                                readOnly: true,
                            });
                            csvExample.setSize("100%", "100%");
                        });
                    </script>

                    <div>
                        <button type="submit" class="button" name="storeTA">Import Students/Assistants/Managers/Teachers</button>
                    </div>
                </form>
            </div>
            <script>
                let typingTimer;
                const doneTypingInterval = 50;
                const editionId = [[${edition.id}]];

                function handleInput() {
                    clearTimeout(typingTimer);
                        const searchInput = document.getElementById('inputIdentifier').value;

                        if (searchInput.trim().length > 2) {
                            typingTimer = setTimeout(() => {
                                fetchData(searchInput)
                                    .then(htmlFragment => {
                                        updateTable(htmlFragment);
                                    })
                                    .catch(error => {
                                        console.error('Error fetching data:', error);
                                        updateTable("<td colspan='5'>An error occurred while fetching the data!</td>");
                                        clearTable();
                                    });
                            }, doneTypingInterval);
                        } else {
                            clearTable();
                        }
                    }

                    function fetchData(identifier) {
                        return fetch(`/edition/${editionId}/search-people?identifier=${identifier}`)
                            .then(response => response.text());
                    }

                    function updateTable(htmlFragment) {
                        const tableContainer = document.getElementById("peopleTable");

                        tableContainer.innerHTML = htmlFragment;
                    }

                    function clearTable() {
                        document.getElementById("peopleTable").innerHTML = '';
                    }
            </script>
        </section>
    </body>
</html>
