<!--

    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="http://www.w3.org/1999/html">
    <!--@thymesVar id="dto" type="nl.tudelft.queue.dto.patch.LabPatchDTO"-->

    <!--@thymesVar id="lSession" type="nl.tudelft.labracore.api.dto.SessionDetailsDTO"-->
    <!--@thymesVar id="lab" type="nl.tudelft.queue.model.labs.Lab"-->

    <!--@thymesVar id="buildings" type="java.util.List<nl.tudelft.labracore.api.dto.BuildingSummaryDTO>"-->
    <!--@thymesVar id="modules" type="java.util.List<nl.tudelft.labracore.api.dto.ModuleDetailsDTO>"-->
    <!--@thymesVar id="assignments" type="java.util.List<nl.tudelft.labracore.api.dto.AssignmentDetailsDTO>"-->
    <!--@thymesVar id="rooms" type="java.util.List<nl.tudelft.labracore.api.dto.RoomDetailsDTO>"-->

    <body>
        <th:block th:object="${dto}">
            <section class="flex vertical" th:fragment="lab-general">
                <div>
                    <h3 class="font-500 mb-3">General</h3>

                    <div class="grid col-2 align-center gap-3" style="--col-1: minmax(0, 8rem)">
                        <label for="title-input">Title</label>

                        <div>
                            <input
                                id="title-input"
                                type="text"
                                class="textfield"
                                required
                                name="name"
                                th:value="${lSession.name}"
                                placeholder="Question session" />
                        </div>

                        <label for="direction-select">Direction:</label>
                        <div>
                            <select data-select id="direction-select" name="communicationMethod">
                                <option
                                    th:each="cm : ${T(nl.tudelft.queue.model.enums.CommunicationMethod).values()}"
                                    th:value="${cm}"
                                    th:text="${cm.displayName}"
                                    th:selected="${lab.communicationMethod == cm}"></option>
                            </select>
                        </div>

                        <th:block th:unless="${qSession.type.name() == 'SLOTTED'}">
                            <span>Slot</span>
                            <div class="flex gap-3">
                                <div class="flex vertical gap-0">
                                    <label for="opens-at" class="input-group-text">From</label>
                                    <input
                                        th:classappend="${#fields.hasErrors('slot.opensAt')} ? 'is-invalid'"
                                        type="datetime-local"
                                        id="opens-at"
                                        name="slot.opensAt"
                                        th:value="${#temporals.format(lSession.start, 'yyyy-MM-dd''T''HH:mm')}"
                                        class="textfield"
                                        required />
                                    <div class="invalid-feedback" th:if="${#fields.hasErrors('slot.opensAt')}" th:errors="*{slot.opensAt}">
                                        Slot opensAt error
                                    </div>
                                </div>

                                <div class="flex vertical gap-0" data-target-input="nearest">
                                    <label for="closes-at" class="input-group-text">To</label>
                                    <input
                                        th:classappend="${#fields.hasErrors('slot.closesAt')} ? 'is-invalid'"
                                        type="datetime-local"
                                        id="closes-at"
                                        name="slot.closesAt"
                                        th:value="${#temporals.format(lSession.endTime, 'yyyy-MM-dd''T''HH:mm')}"
                                        class="textfield"
                                        required />
                                    <div class="invalid-feedback" th:if="${#fields.hasErrors('slot.closesAt')}" th:errors="*{slot.closesAt}">
                                        Slot error
                                    </div>
                                </div>
                            </div>
                        </th:block>
                    </div>
                </div>

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

                <div>
                    <h3 class="font-500 mb-3">Location</h3>

                    <div class="grid col-2 align-center gap-3" style="--col-1: minmax(0, 8rem)">
                        <label for="building-select">Buildings</label>
                        <div>
                            <select multiple data-select id="building-select" data-placeholder="Pick at least one building" onchange="updateRooms()">
                                <th:block th:each="b : ${buildings}">
                                    <option
                                        th:value="${b.id}"
                                        th:text="${b.name}"
                                        th:selected="${!#lists.isEmpty(lSession.rooms.?[building.id == __${b.id}__])}"></option>
                                </th:block>
                            </select>
                        </div>

                        <label for="room-select">Rooms</label>
                        <div>
                            <select multiple data-select id="room-select" name="rooms">
                                <optgroup th:each="building : ${buildings}" th:label="${building.name}">
                                    <option
                                        th:each="room : ${rooms.?[#this.building.id == #root.building.id]}"
                                        th:value="${room.id}"
                                        th:id="|room-${room.id}|"
                                        th:selected="${@labService.containsRoom(lSession, room.id)}"
                                        th:text="|${room.name} (${room.capacity})|"
                                        th:data-building-id="${room.building.id}"></option>
                                </optgroup>
                            </select>
                        </div>

                        <label for="online-mode-select">Online Modes</label>
                        <div>
                            <select multiple data-select id="online-mode-select" name="onlineModes">
                                <th:block th:each="onlineMode : ${T(nl.tudelft.queue.model.enums.OnlineMode).values()}">
                                    <option
                                        th:value="${onlineMode}"
                                        th:selected="${@labService.getOnlineModesInLabSession(lSession.id).contains(onlineMode)}"
                                        th:text="|${onlineMode.getDisplayName()}|"></option>
                                </th:block>
                            </select>
                        </div>
                    </div>
                </div>

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

                <div>
                    <h3 class="font-500 mb-3">Requests</h3>

                    <div class="flex vertical gap-5">
                        <div class="grid col-2 align-center gap-3" style="--col-1: minmax(0, 8rem)">
                            <label for="module-select">Modules</label>
                            <div>
                                <select multiple data-select id="module-select" name="modules" required>
                                    <th:block th:each="m : ${modules}">
                                        <option
                                            th:value="${m.id}"
                                            th:selected="${lab.modules.contains(m.id)}"
                                            th:text="${ec == null} ? ${m.name} : |${editionMap[m.edition.id].course.name} - ${m.name}|"></option>
                                    </th:block>
                                </select>
                            </div>
                        </div>

                        <table id="assignment-and-request-types-table" class="table">
                            <tr class="table__header">
                                <th class="fit-content">Assignment</th>
                                <th>Request types</th>
                            </tr>
                            <tr
                                th:each="assignment : ${assignments}"
                                th:data-a-id="${assignment.id}"
                                th:hidden="${!lab.modules.contains(assignment.module.id)}">
                                <td
                                    class="fit-content single-line"
                                    th:text="${ec == null} ? ${assignment.name} : |${editionMap[moduleMap[assignment.module.id].edition.id].course.name} - ${assignment.name}|"></td>
                                <td>
                                    <select multiple data-select th:name="${'requestTypes[' + assignment.id + ']'}">
                                        <option
                                            th:each="type : ${T(nl.tudelft.queue.model.enums.RequestType).values()}"
                                            th:value="${type}"
                                            th:selected="${@labService.containsAllowedRequest(lab, assignment.id, type)}"
                                            th:text="${type.displayName()}"></option>
                                    </select>
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>

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

                <script th:inline="javascript" type="text/javascript">
                    //<![CDATA[
                    const _modules = /*[[${modules}]]*/ [{ id: "0", assignments: [{ id: "0" }] }];

                    document.addEventListener("ComponentsLoaded", function () {
                        const moduleSelect = document.getElementById("module-select");

                        const opensAtInput = document.getElementById("opens-at");
                        const closesAtInput = document.getElementById("closes-at");

                        if (opensAtInput) {
                            opensAtInput.addEventListener("change", function () {
                                closesAtInput.min = opensAtInput.value;
                                closesAtInput.value = moment(opensAtInput.value).add(225, "minutes").format("YYYY-MM-DD[T]HH:mm");
                            });
                        }

                        moduleSelect.addEventListener("change", function () {
                            const assignments = [...moduleSelect.selectedOptions]
                                .map(opt => opt.value)
                                .flatMap(m => _modules.find(e => e.id.toString() === m).assignments.map(a => a.id.toString()));

                            document
                                .getElementById("assignment-and-request-types-table")
                                .querySelectorAll("tr")
                                .forEach(row => {
                                    if (row.classList.contains("table__header")) return;

                                    const enabled = assignments.includes(row.dataset.aId.toString());
                                    const select = row.querySelector("select");
                                    if (enabled) {
                                        row.removeAttribute("hidden");
                                        select.removeAttribute("disabled");
                                    } else {
                                        row.setAttribute("hidden", "");
                                        select.setAttribute("disabled", "");
                                        [...select.options].forEach(opt => opt.removeAttribute("selected"));
                                    }
                                    select.update();
                                });
                        });
                    });

                    function updateRooms() {
                        const roomSelect = document.getElementById("room-select");
                        const buildings = [...document.getElementById("building-select").selectedOptions].map(opt => opt.value);

                        if (buildings.length === 0) {
                            roomSelect.setAttribute("disabled", "");
                        } else {
                            roomSelect.removeAttribute("disabled");
                        }

                        [...roomSelect.options].forEach(opt => {
                            if (buildings.includes(opt.dataset.buildingId.toString())) {
                                opt.removeAttribute("disabled");
                                opt.removeAttribute("hidden");
                            } else {
                                opt.removeAttribute("selected");
                                opt.setAttribute("hidden", "");
                                opt.setAttribute("disabled", "");
                            }
                        });

                        roomSelect.update();
                    }
                    //]]>
                </script>
            </section>
        </th:block>
    </body>
</html>
