const getStoredTheme = () => localStorage.getItem("theme");
const setStoredTheme = theme => localStorage.setItem("theme", theme);
const getPreferredTheme = () => window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';

$('input[name="themeToggle"]').on("change", function() {
    const selectedTheme = $(this).val();
    setStoredTheme(selectedTheme);
    setThemeIcon(selectedTheme)
    applyTheme(selectedTheme);
});

// on page load
function initThemeChoice() {
    const theme = getStoredTheme() || "auto";  // If the user is new, they won't have a set theme, so default to auto
    setThemeIcon(theme);
    applyTheme(theme);
}

function setThemeIcon(theme) {
    const iconOptions = {
        light: "bi-sun",
        dark: "bi-moon-stars",
        auto: "bi-circle-half"
    }

    if (!Object.keys(iconOptions).includes(theme)) {
        throw new Error(`No icon for theme: ${theme}`);
    }

    $(".js-themeMenuBtn > i").removeClass(Object.values(iconOptions).join(" "));
    $(".js-themeMenuBtn > i").addClass(iconOptions[theme]);
}

function applyTheme(theme) {
    $('input[name="themeToggle"]').siblings("label").removeClass("active");
    $(`input[name="themeToggle"][value="${theme}"]`).siblings("label").addClass("active");

    if (!theme || theme === "auto") {
        theme = getPreferredTheme();
    }

    $("body").attr("data-bs-theme", theme);
}

function getCurrentDateTime() {
    var now = new Date();
    var year = now.getFullYear();
    var month = String(now.getMonth() + 1).padStart(2, '0');
    var day = String(now.getDate()).padStart(2, '0');
    var hours = String(now.getHours()).padStart(2, '0');
    var minutes = String(now.getMinutes()).padStart(2, '0');
    return `${year}-${month}-${day}T${hours}:${minutes}`;
}

// Sanitise a given string to remove HTML, making it DOM safe.
function sanitise(string) {
    if (typeof string !== "string") {
        return string;
    }

    const map = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#x27;',
        "/": '&#x2F;',
    };
    const reg = /[&<>"'/]/ig;
    return string.replace(reg, (match) => map[match]);
  }

$(document).ready(function() {
    // Activate all tooltips
    $('[data-bs-toggle="tooltip"]').tooltip();

    // Activate select2s
    $(".select-2").each(function() {
        $(this).select2({
            theme: "bootstrap",
            minimumResultsForSearch: 10
        });
    });

    $.notify.addStyle("bootstrap", {
        html: 
            '<div class="toast mt-3 overflow-hidden" role="alert">' +
                '<div class="toast-body">' +
                    '<span data-notify-text></span>' +
                '</div>' +
            "</div>"
    });

    $.notify.defaults({
        globalPosition: "bottom right",
        animationType: "fade",
        className: "success"
    });

    // Activate datepickers
    // $(".input-group.date").datepicker({format: "yyyy-mm-dd"});

    // Load theme
    initThemeChoice();
});