<!--

    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/>.

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

    <!--@thymesVar id="qSession" type="nl.tudelft.queue.model.labs.Lab"-->
    <!--@thymesVar id="request" type="nl.tudelft.queue.dto.create.requests.LabRequestCreateDTO"-->

    <!--@thymesVar id="rooms" type="java.util.List<nl.tudelft.labracore.api.dto.RoomDetailsDTO>"-->
    <!--@thymesVar id="assignments" type="java.util.Map<nl.tudelft.labracore.api.dto
.AssignmentSummaryDTO, java.lang.String>"-->
    <!--@thymesVar id="types" type="java.util.Map<java.lang.Long, java.util.Set<java.lang.String>>"-->

    <!--@thymesVar id="message" type="java.lang.String"-->

    <body>
        <th:block th:obj="${request}">
            <div class="flex vertical gap-3" layout:fragment="enqueue-body">
                <div th:if="${qSession.type != T(nl.tudelft.queue.model.enums.QueueSessionType).REGULAR}">
                    <label for="slot-select">Time slot</label>
                    <div id="slot-select" class="slots grid auto-fit" style="--col-width: 8rem">
                        <!--@thymesVar id="qSession" type="nl.tudelft.queue.model.labs.AbstractSlottedLab"-->
                        <style>
                            .slots input:checked + label {
                                background-color: var(--primary-colour);
                                color: var(--on-primary-colour);
                            }
                            .slots input:disabled + label {
                                border-color: var(--disabled-colour);
                                color: var(--disabled-colour);
                            }
                        </style>
                        <th:block th:each="ts : ${qSession.timeSlots}">
                            <!--@thymesVar id="ts" type="nl.tudelft.queue.model.TimeSlot"-->
                            <input
                                hidden
                                th:id="|slot-${ts.id}|"
                                type="radio"
                                th:field="*{timeSlot.id}"
                                th:value="${ts.id}"
                                required
                                th:disabled="${!ts.canTakeSlot()}" />
                            <label
                                th:for="|slot-${ts.id}|"
                                class="inline-block button"
                                data-style="outlined"
                                th:styleappend="${ts.canTakeSlot()} ? '' : 'pointer-events: none;'">
                                <span
                                    th:text="|${#temporals.format(ts.slot.opensAt, 'HH:mm')} - ${#temporals.format(ts.slot.closesAt, 'HH:mm')}|"></span>
                            </label>
                        </th:block>
                    </div>
                </div>

                <div>
                    <label for="input-assignment">Assignment</label>

                    <div>
                        <select id="input-assignment" th:field="*{assignment}" data-placeholder="Pick an assignment" data-select required>
                            <option th:each="entry : ${assignments}" th:value="${entry.key}" th:text="${entry.value}"></option>
                        </select>
                    </div>
                    <div
                        th:each="entry : ${assignments}"
                        th:if="${notEnqueueAble.getOrDefault(entry.key, null) != null}"
                        class="colour-error"
                        style="display: none"
                        th:id="|not-enrolled-${entry.key}|">
                        You're not enrolled for the course containing this assignment. Click
                        <a class="link" th:href="@{/edition/{id}/enrol(id=${notEnqueueAble.get(entry.key)})}">here</a>
                        to enrol.
                    </div>
                    <div
                        th:each="entry : ${assignments}"
                        th:if="${needToJoinGroup.contains(entry.key)}"
                        class="colour-error"
                        style="display: none"
                        th:id="|need-group-${entry.key}|">
                        This assignment uses groups. Join a group
                        <a class="link" th:href="@{/assignment/{id}/groups(id=${entry.key})}">here</a>
                        first to enqueue.
                    </div>
                    <div class="colour-error" th:if="${#fields.hasErrors('assignment')}" th:errors="*{assignment}">Assignment error</div>
                </div>

                <div>
                    <label for="input-type">Type</label>

                    <div>
                        <select
                            class="textfield"
                            id="input-type"
                            th:field="*{requestType}"
                            data-placeholder="Pick a type"
                            data-select
                            required
                            disabled>
                            <option
                                th:each="type : ${T(nl.tudelft.queue.model.enums.RequestType).values()}"
                                th:id="|input-type-${type.name()}|"
                                th:value="${type}"
                                th:text="${type.displayName()}"
                                th:disabled="${qSession.allowedRequests.contains(type)}"></option>
                        </select>
                    </div>

                    <div class="colour-error" th:if="${#fields.hasErrors('requestType')}" th:errors="*{requestType}">Type error</div>
                </div>

                <div id="room-div" th:unless="${#lists.isEmpty(rooms)}" th:classappend="${qSession.enableExperimental ? 'd-none' : ''}">
                    <label for="input-room">Room</label>

                    <div>
                        <select class="textfield" id="input-room" th:field="*{room}" data-select required>
                            <option th:each="room : ${rooms}" th:value="${room.id}" th:text="|${room.building.name} - ${room.name}|"></option>
                        </select>
                    </div>
                    <div class="colour-error" th:if="${#fields.hasErrors('room')}" th:errors="*{room}">Room error</div>
                </div>

                <div
                    id="onlineMode-div"
                    th:unless="${#sets.isEmpty(qSession.onlineModes)}"
                    th:classappend="${qSession.enableExperimental ? 'd-none' : ''}">
                    <label for="input-onlineMode">Online Mode</label>

                    <div>
                        <select class="textfield" id="input-onlineMode" th:field="*{onlineMode}" data-select required>
                            <option
                                th:each="onlineMode : ${qSession.onlineModes}"
                                th:id="|input-onlineMode-${onlineMode.name()}|"
                                th:value="${onlineMode}"
                                th:text="|${onlineMode.getDisplayName()}|"></option>
                        </select>
                    </div>
                    <div class="colour-error" th:if="${#fields.hasErrors('onlineMode')}" th:errors="*{onlineMode}">Online Mode error</div>
                </div>

                <div id="language-div" th:if="${qSession.isBilingual}">
                    <label for="input-language">Language</label>
                    <div>
                        <select id="input-language" data-select name="language">
                            <option selected value="ANY">English</option>
                            <option value="DUTCH_ONLY">Dutch</option>
                        </select>
                    </div>
                </div>

                <div id="question-div" th:classappend="${qSession.enableExperimental ? 'd-none' : ''}">
                    <label for="input-question" class="col-sm-2 control-label">Question</label>
                    <div class="flex vertical gap-1">
                        <textarea
                            minlength="15"
                            maxlength="500"
                            class="textfield"
                            onkeyup="countChar(this)"
                            id="input-question"
                            th:field="*{question}"
                            placeholder="Write your question here"
                            required
                            disabled></textarea>
                        <p id="charCount">0/500</p>
                    </div>
                </div>

                <div id="comment-div" th:classappend="${qSession.enableExperimental ? 'd-none' : ''}">
                    <div class="flex vertical gap-1">
                        <label for="input-comment" id="labelComment">Help your TA find you!</label>

                        <div id="image-holder" class="mt-1 mb-3" hidden>
                            <img alt="Room map" />
                        </div>

                        <textarea
                            maxlength="250"
                            th:classappend="${#fields.hasErrors('comment')} ? 'is-invalid'"
                            class="textfield"
                            id="input-comment"
                            th:field="*{comment}"
                            th:text="${lastKnownLocation}"
                            th:placeholder="'You can use this field to specify a location within the room, e.g. your cubicle number.'"></textarea>

                        <div class="colour-error" th:if="${#fields.hasErrors('comment')}" th:errors="*{comment}">Comment error</div>
                    </div>
                </div>

                <script src="/webjars/momentjs/min/moment.min.js"></script>
                <script src="/js/map_loader.js"></script>

                <script type="text/javascript" th:inline="javascript">
                    function checkEnrolled(val) {
                        $(".enrollment-status").css("display", "none");
                        $("#enqueue").prop("disabled", false);
                        const divError = $(`#not-enrolled-${val}`);
                        if (divError.length) {
                            $("#not-enrolled-" + val).css("display", "block");
                            $("#enqueue").prop("disabled", true);
                        }
                    }

                    function checkGroup(val) {
                        const enqueue = document.getElementById("enqueue");
                        const error = document.getElementById(`need-group-${val}`);
                        enqueue.removeAttribute("disabled");
                        if (error) {
                            error.style.setProperty("display", "block");
                            enqueue.setAttribute("disabled", "");
                        }
                    }

                    document.addEventListener("ComponentsLoaded", function () {
                        //<![CDATA[
                        const typesPerAssignment = /*[[${types}]]*/ { 1: ["bla"] };
                        //]]>

                        const assignmentSelect = document.getElementById("input-assignment");
                        const typeSelect = document.getElementById("input-type");

                        const questionInput = document.getElementById("input-question");
                        const commentInput = document.getElementById("input-comment");

                        const roomSelect = document.getElementById("input-room");
                        const onlineModeSelect = document.getElementById("input-onlineMode");

                        assignmentSelect.addEventListener("change", function () {
                            checkEnrolled(this.value);
                            checkGroup(this.value);

                            typeSelect.querySelectorAll("option").forEach(opt => opt.removeAttribute("selected"));
                            typeSelect.removeAttribute("disabled");

                            const types = typesPerAssignment[this.value].map(s => s.toLowerCase());
                            typeSelect.querySelectorAll("option").forEach(opt => {
                                if (types.includes(opt.value.toLowerCase())) {
                                    opt.removeAttribute("disabled");
                                } else {
                                    opt.setAttribute("disabled", "");
                                }
                            });

                            typeSelect.update();

                            if (/*[[${qSession.enableExperimental}]]*/ false) {
                                $("#room-div")[0].classList.add("d-none");
                                $("#comment-div")[0].classList.add("d-none");
                                $("#enqueue")[0].innerText = "Enqueue";
                                $("#input-room").prop("disabled", false);
                            }
                        });

                        typeSelect.addEventListener("change", function () {
                            if (this.value.toLowerCase() === "question") {
                                questionInput.removeAttribute("disabled");
                            } else {
                                questionInput.setAttribute("disabled", "");
                            }

                            if (/*[[${qSession.enableExperimental}]]*/ false) {
                                if (this.value.toLowerCase() === "question") {
                                    $("#room-div")[0].classList.add("d-none");
                                    $("#comment-div")[0].classList.add("d-none");
                                    $("#enqueue")[0].innerText = "Continue";
                                    $("#input-room").prop("disabled", true);
                                    questionInput.setAttribute("disabled", "");
                                } else {
                                    $("#room-div")[0].classList.remove("d-none");
                                    $("#comment-div")[0].classList.remove("d-none");
                                    $("#enqueue")[0].innerText = "Enqueue";
                                    $("#input-room").prop("disabled", false);
                                }
                            }
                        });

                        if (roomSelect !== null && onlineModeSelect !== null) {
                            roomSelect.addEventListener("change", function () {
                                onlineModeSelect.querySelectorAll("option").forEach(opt => opt.removeAttribute("selected"));
                                roomSelect.setAttribute("required", "");
                                onlineModeSelect.removeAttribute("required");
                                commentInput.removeAttribute("disabled");

                                roomSelect.update();
                                onlineModeSelect.update();
                            });
                            onlineModeSelect.addEventListener("change", function () {
                                roomSelect.querySelectorAll("option").forEach(opt => opt.removeAttribute("selected"));
                                onlineModeSelect.setAttribute("required", "");
                                roomSelect.removeAttribute("required");

                                roomSelect.update();
                                onlineModeSelect.update();
                            });
                        }
                        if (onlineModeSelect !== null) {
                            onlineModeSelect.addEventListener("change", function () {
                                commentInput.value = "";
                                commentInput.setAttribute("disabled", "");
                            });
                        }
                    });
                </script>
            </div>
        </th:block>
    </body>
</html>
