<!--

    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:layout="http://www.w3.org/1999/xhtml">
    <div layout:fragment="code_of_conduct" th:if="${#authenticatedP != null}">
        <dialog class="dialog" id="coc-dialog">
            <div class="p-7 flex vertical">
                <div id="coc-text" class="article"></div>
                <button type="button" class="button" data-type="accept" id="coc-approve" data-cancel>Accept</button>
            </div>
        </dialog>
        <script>
            let supportStorage = false;
            document.addEventListener("DOMContentLoaded", function () {
                let latestDate;
                const today = new Date();
                // Get the start of the academic year for a specific date
                function startOfAcademicYearForDate(date) {
                    return new Date(date.getMonth() >= 9 ? date.getFullYear() : date.getFullYear() - 1 + "-09-01");
                }
                // Check if the date is in the current academic year.
                function currentAcademicYear(date) {
                    return startOfAcademicYearForDate(date).valueOf() !== startOfAcademicYearForDate(today).valueOf();
                }
                // Make sure localStorage is supported by the browser.
                try {
                    latestDate = localStorage.getItem("coc-date");
                    supportStorage = true;
                } catch (e) {
                    if (
                        e instanceof DOMException &&
                        // everything except Firefox
                        (e.code === 22 ||
                            // Firefox
                            e.code === 1014 ||
                            // test name field too, because code might not be present
                            // everything except Firefox
                            e.name === "QuotaExceededError" ||
                            // Firefox
                            e.name === "NS_ERROR_DOM_QUOTA_REACHED")
                    ) {
                        console.info("Browser does not support local storage");
                    }
                    latestDate = null;
                }
                // If the user has not accpted the code of conduct or it has passed on this browser, ask the server if this is indeed the case.
                if (latestDate === null || currentAcademicYear(new Date(latestDate))) {
                    // Make request to server to get the date and CoD.
                    fetch("/profile/code-of-conduct")
                        .then(res => res.json())
                        .then(data => {
                            latestDate = data["dateAccessed"];

                            // If the date has expired, show the code of conduct to the user
                            if (latestDate === null || currentAcademicYear(new Date(latestDate))) {
                                document.getElementById("coc-text").innerHTML = data["codeOfConduct"];
                                document.getElementById("coc-dialog").showModal();
                            }
                        })
                        .catch(err => {
                            console.error("Something went wrong fetching code of conduct");
                        });
                }
            });
            // Store the fact that the user has approved the code of conduct locally and on the server.
            document.getElementById("coc-approve").addEventListener("click", function (event) {
                if (!supportStorage) {
                    localStorage.setItem("coc-date", new Date().toString());
                }
                fetch("/profile/code-of-conduct/update", {
                    method: "POST",
                    headers: {
                        "X-CSRF-TOKEN": csrfToken,
                    },
                });
            });
        </script>
    </div>
</html>
