<!--

    Queue - A Queueing system that can be used to handle labs in higher education
    Copyright (C) 2016-2020  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">
    <!--@thymesVar id="dto" type="nl.tudelft.queue.dto.create.labs.LabCreateDTO"-->

    <!--@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>"-->
    <!--@thymesVar id="buildings" type="java.util.List<nl.tudelft.labracore.api.dto.BuildingSummaryDTO>"-->

    <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="required"
                                th:field="*{name}"
                                placeholder="Question session" />
                        </div>

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

                        <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"
                                    th:field="*{slot.opensAt}"
                                    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"
                                    th:field="*{slot.closesAt}"
                                    class="textfield"
                                    required />
                                <div class="invalid-feedback" th:if="${#fields.hasErrors('slot.closesAt')}" th:errors="*{slot.closesAt}">
                                    Slot error
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

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

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

                    <div class="grid col-2 gap-3 align-center" 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(dto.roomDetails().?[building.id == __${b.id}__])}"></option>
                                </th:block>
                            </select>
                        </div>

                        <label for="room-select">Rooms</label>
                        <div>
                            <select
                                multiple
                                id="room-select"
                                th:field="*{rooms}"
                                data-select
                                th:disabled="${#lists.isEmpty(dto.roomDetails())}"
                                data-placeholder="Pick a room">
                                <th:block th:each="room : ${rooms}">
                                    <option
                                        th:value="${room.id}"
                                        th:id="|room-${room.id}|"
                                        th:selected="${dto.rooms.contains(room.id)}"
                                        th:text="|${room.building.name} - ${room.name} (${room.capacity})|"
                                        th:data-building-id="${room.building.id}"></option>
                                </th:block>
                            </select>
                        </div>
                        <script th:unless="${#lists.isEmpty(dto.roomDetails())}">
                            document.addEventListener("ComponentsLoaded", updateRooms);
                        </script>

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

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

                <div class="flex vertical gap-3">
                    <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
                                    id="module-select"
                                    th:field="*{modules}"
                                    required
                                    data-select
                                    data-placeholder="Pick at least one module">
                                    <th:block th:each="m : ${modules}">
                                        <option
                                            th:value="${m.id}"
                                            th:selected="${dto.modules.contains(m.id)}"
                                            th:text="${ec == null} ? ${m.name} : |${editionMap[m.edition.id].course.name} - ${m.name}|"></option>
                                    </th:block>
                                </select>
                            </div>
                        </div>

                        <p th:if="${#lists.isEmpty(assignments)}" class="colour-error">
                            There are no assignments yet! Click on the "Modules" tab and create one or more assignments in a module first.
                        </p>

                        <table id="assignment-and-request-types-table" th:unless="${#lists.isEmpty(assignments)}" 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="${!dto.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:field="*{requestTypes['__${assignment.id}__']}">
                                        <option
                                            th:each="type : ${T(nl.tudelft.queue.model.enums.RequestType).values()}"
                                            th:value="${type}"
                                            th:selected="${dto.requestTypes.getOrDefault(assignment.id, T(java.util.Set).of()).contains(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");

                        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 => {
                            const visibleElem = document.getElementById(`_room-select__option-${opt.index}`);
                            if (buildings.includes(opt.dataset.buildingId.toString())) {
                                visibleElem.classList.remove("hidden");
                                opt.removeAttribute("disabled");
                            } else {
                                visibleElem.classList.add("hidden");
                                opt.removeAttribute("selected");
                                opt.setAttribute("disabled", "");
                            }
                        });

                        roomSelect.update();
                    }

                    //]]>
                </script>
            </section>
        </th:block>

        <section th:fragment="lab-extra">
            <h3 class="font-500 mb-3"><label for="markdown-editor">Extra lab info</label></h3>
            <div>
                <textarea id="markdown-editor" th:field="*{extraInfo}">some extra info!</textarea>
            </div>

            <div class="mt-500 underlined"></div>

            <script th:inline="javascript" type="text/javascript">
                let ide = new SimpleMDE({
                    element: document.getElementById("markdown-editor"),
                    forceSync: true,
                });
                $("#form").submit(() => {
                    $("#markdown-editor").textContent = ide.value();
                });
            </script>
        </section>
    </body>
</html>
