<!--

    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="~{lab/view.html}">
    <!--@thymesVar id="qSession" type="nl.tudelft.queue.dto.view.LabViewDTO"-->
    <!--@thymesVar id="rooms" type="java.util.List<nl.tudelft.labracore.api.dto.RoomDetailsDTO>"-->
    <!--@thymesVar id="assignments" type="java.util.List<nl.tudelft.labracore.api.dto.AssignmentDetailsDTO>"-->

    <head>
        <title th:text="'Status - Session #' + ${qSession.id}"></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/chart_utils.js"></script>
        <script src="/js/session_status.js"></script>
        <script src="/js/lab_session_status_common.js"></script>
    </head>

    <body>
        <section layout:fragment="subcontent">
            <h3 class="font-500 mb-3" th:text="'Status - Session #' + ${qSession.id}"></h3>

            <div id="generic-filter" class="stat-filter-form">
                <form id="generic-filter-form" method="get" class="flex wrap gap-3 mb-5">
                    <div class="flex wrap space-between align-center">
                        <div class="flex align-center" th:if="${qSession.session.edition == null}">
                            <label for="course-filter">Courses:</label>
                            <select multiple id="course-filter" data-select name="editions" class="textfield">
                                <option
                                    th:each="courseEntry : ${editionsToCourses}"
                                    th:value="${courseEntry.key}"
                                    th:text="|${courseEntry.value.code}|"></option>
                            </select>
                        </div>
                        <div class="flex align-center">
                            <label for="nMinutes">Bucket Duration (min):</label>
                            <input id="nMinutes" name="nMinutes" type="text" class="textfield" placeholder="15" />
                        </div>
                        <div class="flex align-end">
                            <button type="submit" class="button">Filter</button>
                        </div>
                    </div>
                </form>
            </div>

            <div class="flex align-center">
                <section id="general-information" class="flex wrap align-center align-stretch content-wrapper mb-3 gap-2">
                    <div class="surface content-wrapper">
                        <div class="surface__content flex vertical align-center gap-0">
                            <h3 class="font-300">
                                <span id="card-request-count">-1</span>
                                Requests
                            </h3>
                            <h4 class="font-100">
                                <span id="card-submission-count">-1</span>
                                Submissions |
                                <span id="card-question-count">-1</span>
                                Questions
                            </h4>
                        </div>
                    </div>

                    <div class="surface content-wrapper">
                        <div class="surface__content flex justify-center">
                            <h3 class="font-400 flex vertical align-center">
                                Currently Enqueued
                                <span id="card-enqueued-count">-1</span>
                            </h3>
                        </div>
                    </div>

                    <div class="surface content-wrapper">
                        <div class="surface__content flex justify-center">
                            <h3 class="font-400 flex vertical align-center">
                                Average Waiting Time
                                <span id="card-waiting-time">-1</span>
                            </h3>
                        </div>
                    </div>

                    <div class="surface content-wrapper">
                        <div class="surface__content flex justify-center">
                            <h3 class="font-400 flex vertical align-center">
                                Average Processing Time
                                <span id="card-processing-time">-1</span>
                            </h3>
                        </div>
                    </div>
                </section>
            </div>

            <div class="flex vertical mb-3">
                <table class="table" id="assistant-frequency-table" data-style="surface">
                    <thead>
                        <tr class="table__header">
                            <th>
                                Teaching Assistant
                                <button class="p-min button ml-2" data-style="outlined" onclick="sortTable(0)">Sort</button>
                            </th>
                            <th>
                                Number of Requests
                                <button class="p-min button ml-2" data-style="outlined" onclick="sortTable(1)">Sort</button>
                            </th>
                            <th>
                                Time Since Previous Request Interaction
                                <button class="p-min button ml-2" data-style="outlined" onclick="sortTable(2)">Sort</button>
                            </th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>

            <section id="chart-sec-1" class="grid col-2 | md:col-1">
                <div class="surface p-0">
                    <h5 class="surface__header">Assignment Breakdown</h5>
                    <div class="surface__content">
                        <canvas id="assignment-frequency-canvas" height="400px" width="500px"></canvas>
                    </div>
                </div>

                <div class="surface p-0">
                    <h5 class="surface__header">Request Distribution Over Time</h5>
                    <div class="surface__content">
                        <canvas id="request-distribution-canvas" height="400px" width="500px"></canvas>
                    </div>
                </div>

                <div class="surface p-0">
                    <h5 class="surface__header">Building Distribution Over Time</h5>
                    <div class="surface__content">
                        <canvas id="building-distribution-canvas" height="400px" width="500px"></canvas>
                    </div>
                </div>

                <div class="surface p-0">
                    <h5 class="surface__header">Average Processing and Wait Times</h5>
                    <div class="surface__content">
                        <canvas id="time-distribution-canvas" height="400px" width="500px"></canvas>
                    </div>
                </div>
            </section>

            <script th:inline="javascript" type="text/javascript">
                const TIMEOUT_INTERVAL_TIME = 10000;
                let timeOutInterval;
                $(document).ready(() => {
                    update();
                    timeOutInterval = setInterval(update, TIMEOUT_INTERVAL_TIME);
                });

                $(".stat-filter-form").on("submit", e => {
                    e.preventDefault();
                    clearInterval(timeOutInterval);
                    update();
                    timeOutInterval = setInterval(update, TIMEOUT_INTERVAL_TIME);
                });

                /**
                 * Fetches data and updates the statistics.
                 */
                function update() {
                    const qSessionId = [[${qSession.id}]];
                    const genericFilterForm = $("#generic-filter-form");

                    // TODO figure out a better way to batch these API requests later.
                    const generalUrl = `/lab/${qSessionId}/status/general`;
                    fetch(withParameters(generalUrl, genericFilterForm))
                        .then(response => response.json())
                        .then(updateGeneralInformation($("#general-information")))

                    const assistantFreqUrl = `/lab/${qSessionId}/status/assistant/freq`;
                    fetch(withParameters(assistantFreqUrl, genericFilterForm))
                        .then(response => response.json())
                        .then(updateAssistantFrequencyTable($("#assistant-frequency-table")));

                    const assignmentFreqUrl = `/lab/${qSessionId}/status/assignment/freq`
                    fetch(withParameters(assignmentFreqUrl, genericFilterForm))
                        .then(response => response.json())
                        .then(updateAssignmentFrequencyChart($("#assignment-frequency-canvas")));

                    const requestDistributionUrl=`/lab/${qSessionId}/status/request/distribution`;
                    fetch(withParameters(requestDistributionUrl, genericFilterForm))
                        .then(response => response.json())
                        .then(updateDistributionChart($("#request-distribution-canvas"), "requestDistributionChart", "bar", true))

                    const buildingDistributionUrl = `/lab/${qSessionId}/status/building/distribution`;
                    fetch(withParameters(buildingDistributionUrl, genericFilterForm))
                        .then(response => response.json())
                        .then(updateDistributionChart($("#building-distribution-canvas"), "buildingDistributionChart", "line", false))

                    const timeDistributionUrl = `/lab/${qSessionId}/status/time/distribution`;
                    fetch(withParameters(timeDistributionUrl, genericFilterForm))
                        .then(response => response.json())
                        .then(updateDistributionChart($("#time-distribution-canvas"), "timeDistributionChart", "line", false, "Minutes"))
                }

                /**
                 * Appends parameters to a URL specified by the user using the form.
                 *
                 * @param url The url to append to
                 * @param paramForm The form to consider.
                 */
                function withParameters(url, paramForm) {
                    if (paramForm) {
                        url += "?";
                        url += new URLSearchParams(paramForm.serialize());
                    }
                    return url;
                }

                // Code taken from W3Schools
                function sortTable(n) {
                    let table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
                    table = document.getElementById("assistant-frequency-table")
                    switching = true;
                    // Set the sorting direction to ascending:
                    dir = "asc";
                    /* Make a loop that will continue until
                    no switching has been done: */
                    while (switching) {
                        // Start by saying: no switching is done:
                        switching = false;
                        rows = table.rows;
                        /* Loop through all table rows (except the
                        first, which contains table headers): */
                        for (i = 1; i < (rows.length - 1); i++) {
                            // Start by saying there should be no switching:
                            shouldSwitch = false;
                            /* Get the two elements you want to compare,
                            one from current row and one from the next: */
                            x = rows[i].getElementsByTagName("td")[n];
                            y = rows[i + 1].getElementsByTagName("td")[n];
                            /* Check if the two rows should switch place,
                            based on the direction, asc or desc: */
                            if (dir == "asc") {
                                if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
                                    // If so, mark as a switch and break the loop:
                                    shouldSwitch = true;
                                    break;
                                }
                            } else if (dir == "desc") {
                                if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
                                    // If so, mark as a switch and break the loop:
                                    shouldSwitch = true;
                                    break;
                                }
                            }
                        }
                        if (shouldSwitch) {
                            /* If a switch has been marked, make the switch
                            and mark that a switch has been done: */
                            rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
                            switching = true;
                            // Each time a switch is done, increase this count by 1:
                            switchcount ++;
                        } else {
                            /* If no switching has been done AND the direction is "asc",
                            set the direction to "desc" and run the while loop again. */
                            if (switchcount == 0 && dir == "asc") {
                                dir = "desc";
                                switching = true;
                            }
                        }
                    }
                }
            </script>
        </section>
    </body>
</html>
