<!--

    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">
    <!--@thymesVar id="#authenticatedP" type="nl.tudelft.labracore.lib.security.user.Person"-->

    <!--@thymesVar id="qSession" type="nl.tudelft.queue.dto.view.labs.AbstractSlottedLabViewDTO"-->

    <!--@thymesVar id="distributeRequestsDto" type="nl.tudelft.queue.dto.util.DistributeRequestsDTO"-->

    <body>
        <div th:fragment="slots-info">
            <div th:if="${@permissionService.canManageSession(qSession.data)}" class="tabs mb-5" role="tablist">
                <button type="button" role="tab" aria-controls="basic-tab" aria-selected="true">
                    <i class="fa fa-calendar"></i>
                    Overview
                </button>
                <button type="button" role="tab" aria-controls="ts-edit-tab" aria-selected="false">
                    <i class="fa fa-edit"></i>
                    Edit
                </button>
                <button type="button" role="tab" aria-controls="ts-distribution-tab" aria-selected="false">
                    <i class="fa fa-users-cog"></i>
                    Distribute Requests
                </button>
            </div>

            <div id="basic-tab">
                <div id="slot-overview"></div>
            </div>

            <div id="ts-edit-tab" th:if="${@permissionService.canManageSession(qSession.data)}">
                <div class="flex">
                    <div id="edit-day-overview" class="grow"></div>
                    <div class="flex vertical">
                        <div id="edit-info" class="banner" data-type="info">
                            <span class="fa-solid fa-info-circle banner__icon"></span>
                            <p>Click a time slot to edit</p>
                        </div>
                        <div id="edit-timeslot" class="flex vertical hidden">
                            <h3 class="flex vertical gap-0">
                                <span id="edit-timeslot-time" class="font-500"></span>
                                <span id="edit-timeslot-day" class="font-500"></span>
                            </h3>
                            <div class="grid col-2 align-center gap-3" style="--col-1: 6rem">
                                <label for="edit-timeslot-capacity">Capacity</label>
                                <input id="edit-timeslot-capacity" class="textfield" min="0" type="number" />
                            </div>
                            <button id="remove-timeslot" type="button" class="button" data-style="outlined" data-type="error">Remove slot</button>
                        </div>
                    </div>
                </div>
            </div>

            <script th:inline="javascript">
                document.addEventListener("DOMContentLoaded", function () {
                    let timeSlots = new TimeSlotCollection();
                    let canManage = /*[[${@permissionService.canManageSession(qSession.data)}]]*/ false;

                    // Add slots from DTO
                    const slotDTOs = /*[[${qSession.timeSlots}]]*/ [];
                    const canTake = /*[[${qSession.timeSlots.![#this.canTakeSlot()]}]]*/ [];
                    for (let i = 0; i < slotDTOs.length; i++) {
                        let slot = TimeSlot.fromDTO(slotDTOs[i], true);
                        slot.showCapacity = canManage;
                        slot.showRequests = canManage;
                        slot.untakable = !canTake[i];
                        slot.preventEditing = slot.requests.length > 0;
                        slot.synched = true; // Sync with server
                        timeSlots.addSlot(slot);
                    }
                    let range = timeSlots.range;

                    // Overview calendar
                    const slotOverview = new Calendar(
                        new FullCalendar.Calendar(document.getElementById("slot-overview"), {
                            initialView: "timeGridSomeDays",
                            locale: "gb",
                            firstDay: 1,
                            slotDuration: "00:10",
                            allDaySlot: false,
                            nowIndicator: true,
                            headerToolbar: {
                                left: "title",
                                right: "prev,next",
                            },
                            validRange: {
                                start: range.start.toDate(),
                                end: range.end.toDate(),
                            },
                            views: {
                                timeGridSomeDays: {
                                    type: "timeGrid",
                                    duration: { days: Math.min(7, range.end.diff(range.start, "days")) },
                                },
                            },
                            scrollTime: timeSlots.timeRange.start,
                        }),
                        timeSlots
                    );
                    slotOverview.show();
                    // Make sure slot overview is not hidden when updating
                    slotOverview.update = function () {
                        document.getElementById("basic-tab").removeAttribute("hidden");
                        this.calendar.refetchEvents();
                        document.getElementById("basic-tab").setAttribute("hidden", "");
                    };

                    // Edit calendar
                    const editDayOverview = new Calendar(
                        new FullCalendar.Calendar(document.getElementById("edit-day-overview"), {
                            initialView: "timeGridDay",
                            locale: "gb",
                            firstDay: 1,
                            slotDuration: "00:10",
                            allDaySlot: false,
                            nowIndicator: true,
                            editable: true,
                            headerToolbar: {
                                left: "title",
                                right: "prev,next",
                            },
                            validRange: {
                                start: range.start.toDate(),
                                end: range.end.toDate(),
                            },
                            scrollTime: timeSlots.timeRange.start,
                        }),
                        timeSlots,
                        {
                            // On select display event editing on the side
                            onSelect: ts => {
                                const from = ts.start.format("H:mm");
                                const to = ts.end.format("H:mm");

                                document.getElementById("edit-timeslot-day").innerText = ts.start.format("dddd D MMMM");
                                document.getElementById("edit-timeslot-time").innerText = `${from} - ${to}`;
                                document.getElementById("edit-timeslot-capacity").value = ts.capacity;

                                document.getElementById("edit-timeslot").classList.remove("hidden");
                                document.getElementById("edit-info").classList.add("hidden");

                                if (ts.requests.length > 0) {
                                    document.getElementById("remove-timeslot").setAttribute("disabled", "");
                                } else {
                                    document.getElementById("remove-timeslot").removeAttribute("disabled", "");
                                }
                            },
                            // Allow editing
                            onEdit: () => {},
                        }
                    );
                    editDayOverview.show();

                    document.getElementById("ts-edit-tab").setAttribute("hidden", "");

                    // Update when capacity is changed
                    const editCapacity = document.getElementById("edit-timeslot-capacity");
                    editCapacity.addEventListener("change", function () {
                        const timeSlot = timeSlots.selected;
                        timeSlot.capacity = parseInt(editCapacity.value);
                    });

                    // Delete event when remove button is pressed
                    document.getElementById("remove-timeslot").addEventListener("click", function () {
                        if (timeSlots.selected.requests.length > 0) return;

                        timeSlots.removeSlot(timeSlots.selected);

                        document.getElementById("edit-timeslot").classList.add("hidden");
                        document.getElementById("edit-info").classList.remove("hidden");
                        editDayOverview.update();
                    });

                    // Deselected when switching back to overview
                    document.querySelector("[aria-controls='basic-tab']").addEventListener("click", function () {
                        timeSlots.deselect();

                        document.getElementById("edit-timeslot").classList.add("hidden");
                        document.getElementById("edit-info").classList.remove("hidden");
                        editDayOverview.update();
                    });
                });
            </script>

            <th:block th:if="${@permissionService.canManageSession(qSession.data)}">
                <div id="ts-distribution-tab" hidden>
                    <div class="flex vertical gap-5">
                        <h2 class="font-600 fw-400">Distribute Requests</h2>
                        <div class="banner" data-type="info">
                            <span class="fa-solid fa-info-circle"></span>
                            <p>
                                Distribute pending requests relating to specific assignments in a round-robin fashion among selected assistants. The
                                distribution will be done in the order of the assistants selected.
                            </p>
                        </div>

                        <form
                            th:object="${distributeRequestsDto}"
                            th:action="@{/lab/{id}/distribute(id=${qSession.id})}"
                            th:method="POST"
                            class="flex vertical gap-5">
                            <div id="distribute-edition-cards" class="flex vertical space-between">
                                <th:block th:each="edition, editionItemStat : ${qSession.session.editions}">
                                    <div
                                        class="surface p-0"
                                        th:id="'distribute-card-' + ${edition.id}"
                                        th:if="${@permissionService.canManageEdition(edition.id)}">
                                        <h3 class="surface__header" th:text="${editionsToCourses.get(edition.id).name}"></h3>

                                        <div class="surface__content">
                                            <div class="grid col-2 align-center" style="--col-1: minmax(0, 10rem)">
                                                <label th:for="'assignment-distribute-select-' + ${edition.id}">Select Assignments</label>
                                                <div>
                                                    <select
                                                        data-select
                                                        multiple
                                                        class="textfield"
                                                        data-style="variant"
                                                        th:id="'assignment-distribute-select-' + ${edition.id}"
                                                        data-title="Select assignment(s) to distribute"
                                                        th:field="*{editionSelections[__${editionItemStat.index}__].selectedAssignments}">
                                                        <th:block
                                                            th:each="assignment : ${@moduleDTOService.getAssignmentsInEdition(modules, edition.id)}">
                                                            <option th:value="${assignment.id}" th:text="|${assignment.name}|"></option>
                                                        </th:block>
                                                    </select>
                                                </div>

                                                <label th:for="'assistant-distribute-select-' + ${edition.id}">Select Assistants</label>
                                                <div>
                                                    <select
                                                        data-select
                                                        multiple
                                                        class="textfield"
                                                        data-style="variant"
                                                        th:id="'assistant-distribute-select-' + ${edition.id}"
                                                        data-title="Select assistant(s) to distribute among"
                                                        th:field="*{editionSelections[__${editionItemStat.index}__].selectedAssistants}">
                                                        <th:block th:each="person : ${@roleDTOService.staff(edition)}">
                                                            <option th:value="${person.id}" th:text="${person.displayName}"></option>
                                                        </th:block>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </th:block>
                            </div>

                            <div>
                                <button type="submit" data-type="primary" data-style="filled" class="button">Distribute Requests</button>
                            </div>
                        </form>
                    </div>
                </div>
            </th:block>

            <script type="text/javascript" src="/js/form_submission_enhancer.js"></script>
        </div>
    </body>
</html>
