<!--

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

-->
<!DOCTYPE html>
<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="activeLabs" type="java.util.List<nl.tudelft.queue.dto.view.QueueSessionSummaryDTO>"-->
    <!--@thymesVar id="inactiveLabs" type="java.util.List<nl.tudelft.queue.dto.view.QueueSessionSummaryDTO>"-->

    <!--@thymesVar id="assignments" type="java.util.List<nl.tudelft.labracore.api.dto.AssignmentSummaryDTO>"-->
    <!--@thymesVar id="rooms" type="java.util.List<nl.tudelft.labracore.api.dto.RoomDetailsDTO>"-->

    <!--@thymesVar id="assistants" type="java.util.List<nl.tudelft.queue.dto.view.statistics.AssistantRatingViewDto>"-->

    <!--@thymesVar id="requestType" type="nl.tudelft.queue.model.enums.RequestType"-->

    <head>
        <title th:text="|Status - ${edition.course.name} (${edition.name})|"></title>

        <script src="/webjars/momentjs/min/moment.min.js"></script>
        <script src="/webjars/chartjs/dist/chart.umd.js"></script>
        <script src="/webjars/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
        <script src="/js/lab_session_status_common.js"></script>
        <script src="/js/chart_utils.js"></script>
    </head>

    <body>
        <section layout:fragment="subcontent">
            <h3 class="font-500 mb-3">Statistics</h3>

            <div class="tabs mb-5" role="tablist">
                <button id="labs-tab" aria-controls="labs" role="tab" aria-selected="true">Sessions</button>
                <button id="assistants-tab" aria-controls="assistants" role="tab" aria-selected="false">Assistants</button>
            </div>

            <div id="labs">
                <th:block th:unless="${#lists.isEmpty(activeLabs) && #lists.isEmpty(inactiveLabs)}">
                    <form id="lab-form" method="get" class="flex wrap gap-3 mb-5">
                        <div>
                            <label for="lab-select-lab">Session:</label>
                            <div>
                                <select multiple id="lab-select-lab" data-select name="labs">
                                    <optgroup label="Active">
                                        <option
                                            th:each="lab : ${activeLabs}"
                                            th:value="${lab.id}"
                                            th:text="|${lab.name} - ${#temporals.format(lab.slot.opensAt, 'd MMMM')}|"
                                            selected></option>
                                    </optgroup>
                                    <optgroup label="Old">
                                        <option
                                            th:each="lab : ${inactiveLabs}"
                                            th:value="${lab.id}"
                                            th:text="|${lab.name} - ${#temporals.format(lab.slot.opensAt, 'd MMMM')}|"
                                            selected></option>
                                    </optgroup>
                                </select>
                            </div>
                        </div>
                        <div>
                            <label for="lab-select-assignment">Assignment:</label>
                            <div>
                                <select multiple id="lab-select-assignment" data-select name="assignments">
                                    <option
                                        th:each="assignment : ${assignments}"
                                        th:value="${assignment.id}"
                                        th:text="${assignment.name}"
                                        selected></option>
                                </select>
                            </div>
                        </div>
                        <div>
                            <label for="lab-select-room">Room:</label>
                            <div>
                                <select multiple id="lab-select-room" data-select name="rooms">
                                    <option
                                        th:each="room : ${rooms}"
                                        th:value="${room.id}"
                                        th:text="|${room.building.name} - ${room.name}|"
                                        selected></option>
                                </select>
                            </div>
                        </div>
                        <div>
                            <label for="lab-request-type">Request type:</label>
                            <div>
                                <select multiple id="lab-request-type" data-select name="type">
                                    <th:block th:each="requestType : ${T(nl.tudelft.queue.model.enums.RequestType).values()}">
                                        <option th:value="${requestType.name()}" th:text="${requestType.displayName()}" selected></option>
                                    </th:block>
                                </select>
                            </div>
                        </div>
                        <div class="flex align-end">
                            <button type="submit" class="button">Filter</button>
                        </div>
                    </form>

                    <div class="grid col-2 mb-5 | md:col-1">
                        <table class="table" data-style="surface">
                            <tr class="table__header">
                                <th>Name</th>
                                <th>Value</th>
                            </tr>
                            <tr>
                                <td>Number of students participating in the lab(s)</td>
                                <td id="lab-static-noStudents">-1</td>
                            </tr>
                            <tr>
                                <td>Number of assistants working the lab(s)</td>
                                <td id="lab-static-noAssistants">-1</td>
                            </tr>
                            <tr>
                                <td>Number of requests currently open</td>
                                <td id="lab-static-nOpen">-1</td>
                            </tr>
                            <tr>
                                <td>Number of requests handled during the lab(s)</td>
                                <td id="lab-static-nHandled">-1</td>
                            </tr>
                        </table>
                        <table class="table" data-style="surface">
                            <tr class="table__header">
                                <th>Name</th>
                                <th>Value</th>
                            </tr>
                            <tr>
                                <td>Most popular assignment</td>
                                <td id="lab-static-assignment">N.A.</td>
                            </tr>
                            <tr>
                                <td>Most popular room</td>
                                <td id="lab-static-room">N.A.</td>
                            </tr>
                            <tr>
                                <td>Average waiting time for the last hour</td>
                                <td id="lab-static-avgWaitingTime">N.A.</td>
                            </tr>
                            <tr>
                                <td>Average processing time in the last hour</td>
                                <td id="lab-static-avgProcessingTime">N.A.</td>
                            </tr>
                        </table>
                    </div>

                    <div class="grid col-2 | md:col-1">
                        <div class="surface p-0">
                            <h5 class="surface__header">Requests over time</h5>
                            <div class="surface__content">
                                <canvas id="lab-canvas-rf" height="300px"></canvas>
                            </div>
                        </div>
                        <div class="surface p-0">
                            <h5 class="surface__header">Request status frequencies</h5>
                            <div class="surface__content">
                                <canvas id="lab-canvas-sf" height="300px"></canvas>
                            </div>
                        </div>
                        <div class="surface p-0">
                            <h5 class="surface__header">Assignment request counts</h5>
                            <div class="surface__content">
                                <canvas id="lab-canvas-af" height="300px"></canvas>
                            </div>
                        </div>
                        <div class="surface p-0">
                            <h5 class="surface__header">Room request counts</h5>
                            <div class="surface__content">
                                <canvas id="lab-canvas-rof" height="300px"></canvas>
                            </div>
                        </div>
                        <div class="surface p-0">
                            <h5 class="surface__header">Request counts per lab</h5>
                            <div class="surface__content">
                                <canvas id="lab-canvas-lof" height="300px"></canvas>
                            </div>
                        </div>

                        <div class="surface p-0">
                            <h5 class="surface__header">Average wait and processing times per lab</h5>
                            <div class="surface__content">
                                <canvas id="lab-canvas-awp" height="300px"></canvas>
                            </div>
                        </div>
                    </div>
                </th:block>

                <div th:if="${#lists.isEmpty(activeLabs) && #lists.isEmpty(inactiveLabs)}">
                    <h5>No labs</h5>
                </div>
            </div>

            <div id="assistants" hidden>
                <form id="assistant-form" method="get" class="mb-5">
                    <div>
                        <label for="lab-select-assistants">Lab</label>
                        <select multiple id="lab-select-assistants" data-select name="labs">
                            <optgroup label="Active">
                                <option
                                    th:each="lab : ${activeLabs}"
                                    th:value="${lab.id}"
                                    th:text="|${lab.name} - ${#temporals.format(lab.slot.opensAt, 'd MMMM')}|"
                                    selected></option>
                            </optgroup>
                            <optgroup label="Old">
                                <option
                                    th:each="lab : ${inactiveLabs}"
                                    th:value="${lab.id}"
                                    th:text="|${lab.name} - ${#temporals.format(lab.slot.opensAt, 'd MMMM')}|"
                                    selected></option>
                            </optgroup>
                        </select>
                    </div>
                </form>

                <div id="assistant-table">
                    <table class="table" data-style="surface">
                        <tr class="table__header">
                            <th>Assistant</th>
                            <th>Requests Handled</th>
                            <th>Average Rating</th>
                        </tr>
                        <tr th:each="assistant : ${assistants}">
                            <td th:text="${assistant.person.displayName}"></td>
                            <td th:text="${assistant.numberOfRequests}"></td>

                            <td>
                                <div style="display: inline-flex; justify-content: space-between">
                                    <th:block th:if="${assistant.numberOfRequests <2}">
                                        <p>Not enough feedback (yet)</p>
                                    </th:block>
                                    <th:block th:if="${assistant.numberOfRequests >=2}">
                                        <div class="flex gap-0 font-500" style="color: goldenrod">
                                            <span
                                                class="fa-solid fa-star"
                                                th:each="_ : ${#numbers.sequence(1, assistant.getNumFilledStars(), 1)}"></span>

                                            <span th:if="${assistant.hasHalfFilledStar()}" class="fa-solid fa-star-half-stroke"></span>

                                            <span
                                                class="fa-regular fa-star"
                                                th:each="_ : ${#numbers.sequence(1, assistant.getNumEmptyStars(), 1)}"></span>
                                        </div>
                                        <p th:text="${assistant.avgRating}" style="margin-left: 10px"></p>
                                    </th:block>
                                </div>
                            </td>
                        </tr>
                    </table>
                </div>
            </div>

            <script th:inline="javascript" type="text/javascript">
                $(function () {
                    let rfFormSubmitTimeout;

                    $("#lab-form").on("submit", function (e) {
                        e.preventDefault();
                        clearTimeout(rfFormSubmitTimeout);
                        rfFormSubmitTimeout = setTimeout(updateLabPanel, 2000);
                    });

                    $("#assistant-form").on("submit", function (e) {
                        e.preventDefault();
                        clearTimeout(rfFormSubmitTimeout);
                        rfFormSubmitTimeout = setTimeout(updateAssistantTable, 2000);
                    });

                    updateLabPanel();
                    updateAssistantTable();

                    const assistantSelector = $("#assistants select");
                    showLabCount(assistantSelector.children("option:selected").val());
                    assistantSelector.on("change", function () {
                        showLabCount($(this).children("option:selected").val());
                    });
                });

                function showLabCount(id) {
                    $(".table-container table").hide();
                    $("#table-" + id).show();
                }

                function updateLabInfo(data) {
                    $("#lab-static-noStudents").text(data.numStudents);
                    $("#lab-static-noAssistants").text(data.numAssistants);
                    $("#lab-static-nOpen").text(data.numOpen);
                    $("#lab-static-nHandled").text(data.numHandled);
                    $("#lab-static-assignment").text(data.assignment);
                    $("#lab-static-room").text(data.room);
                    $("#lab-static-avgWaitingTime").text(msToHumanReadableTime(data.avgWaitingTime));
                    $("#lab-static-avgProcessingTime").text(msToHumanReadableTime(data.avgProcessingTime));
                }

                function updateLabPanel() {
                    const labForm = $("#lab-form");

                    $.ajax({
                        type: labForm.attr("method"),
                        data: labForm.serialize(),
                        url: /*[[@{/edition/{id}/status/lab/info(id = ${edition.id})}]]*/ "/editions",
                        success: updateLabInfo,
                    });

                    $.ajax({
                        type: labForm.attr("method"),
                        data: labForm.serialize(),
                        url: /*[[@{/edition/{id}/status/freq/request(id = ${edition.id})}]]*/ "/editions",
                        success: drawRequestFreqChart($("#lab-canvas-rf")),
                    });

                    $.ajax({
                        type: labForm.attr("method"),
                        data: labForm.serialize(),
                        url: /*[[@{/edition/{id}/status/freq/status(id = ${edition.id})}]]*/ "/editions",
                        success: drawStatusFreqChart($("#lab-canvas-sf")),
                    });

                    $.ajax({
                        type: labForm.attr("method"),
                        data: labForm.serialize(),
                        url: /*[[@{/edition/{id}/status/freq/assignment(id = ${edition.id})}]]*/ "/editions",
                        success: updateAssignmentFrequencyChart($("#lab-canvas-af")),
                    });

                    $.ajax({
                        type: labForm.attr("method"),
                        data: labForm.serialize(),
                        url: /*[[@{/edition/{id}/status/freq/room(id = ${edition.id})}]]*/ "/editions",
                        success: drawRoomFreqChart($("#lab-canvas-rof")),
                    });

                    $.ajax({
                        type: labForm.attr("method"),
                        data: labForm.serialize(),
                        url: /*[[@{/edition/{id}/status/lab/freq(id = ${edition.id})}]]*/ "/editions",
                        success: updateLabFreqChart($("#lab-canvas-lof")),
                    });

                    $.ajax({
                        type: labForm.attr("method"),
                        data: labForm.serialize(),
                        url: /*[[@{/edition/{id}/status/lab/time(id = ${edition.id})}]]*/ "/editions",
                        success: updateLabTimeChart($("#lab-canvas-awp")),
                    });
                }

                function updateAssistantTable() {
                    const assistantForm = $("#assistant-form");
                    $.ajax({
                        type: assistantForm.attr("method"),
                        data: assistantForm.serialize(),
                        url: /*[[@{/edition/{id}/status/freq/assistant(id = ${edition.id})}]]*/ "/editions",
                        success: fragment => $("#assistant-table").replaceWith(fragment),
                    });
                }
            </script>
        </section>
    </body>
</html>
