$(document).ready(function () {
    // Your code here
    console.log("log.js is loaded and ready.");
    let $logchooser = $('#logchooser');
    // if logchooser value is null, set to today's date in format mm/dd/yyyy
    if ($logchooser.val() === null) {
        $logchooser.val(new Date().toISOString().split('T')[0]);
    }

    $('#logoutbtn').on('click', function () {
        // Clear session storage on logout
        fetch('/logout').then(() => {
            window.location.href = '/login.html';
        });
    });
    $logchooser.on('change', function () {
        const selectedLog = $(this).val();
        GetLog(selectedLog);
    });
});

$(window).on('unload', function () {
    console.log("User is leaving log.html");
    // Your cleanup code here
});

// function GetLog with date parameter in string, with default value today's date in format dd/mm/yyyy
function GetLog(date = new Date().toISOString().split('T')[0]) {
    console.log("Fetching logs for date: " + date);
    Get('getLogs?' + new URLSearchParams({ date: date }).toString(), function (data) {
        console.log(data);
        fill_table(data);
    }, function (error) {
        fill_table(null);
        alert(error);
    })
}

/**
 * @typedef {Object} logdata
 * @property {number} index Index number of the log entry
 * @property {string} date Date string in format dd/mm/yyyy
 * @property {string} time Time string in format HH:MM:SS
 * @property {string} function Function name where the log was generated
 * @property {string} message Log message
 */

/**
 * Fill table with logdata
 * @param {logdata[]} data 
 */
function fill_table(data) {
    let $logtablebody = $('#logtablebody');
    $logtablebody.empty();
    if (data && Array.isArray(data) && data.length > 0) {
        data.forEach(function (logentry) {
            let row = `<tr>
            <td>${logentry.index}</td>
            <td>${logentry.date}</td>
            <td>${logentry.time}</td>
            <td>${logentry.function}</td>
            <td>${logentry.message}</td>
        </tr>`;
            $logtablebody.append(row);
        });
    }

}