/**
 * @typedef {Object} Log
 * @property {number} index
 * @property {string} datenya
 * @property {string} timenya
 * @property {string} machine
 * @property {string} description
 */

/** List of Log data loaded from server
 * @type {Log[]}
 */
window.logdata = [];

/**
 * Fill log table body with values
 * @param {Log[]} vv values to fill
 */
function fill_logtablebody(vv) {
    $('#logtablebody').empty();
    
    if (!Array.isArray(vv) || vv.length === 0) {
        $('#btnExport').prop('disabled', true);
        return;
    }
    vv.forEach(item => {
        const row = `<tr>
                     <td>${item.index}</td>
                     <td>${item.datenya}</td>
                     <td>${item.timenya}</td>
                     <td>${item.machine}</td>
                     <td>${item.description}</td>
                     </tr>`;
        $('#logtablebody').append(row);
    });
    $('#tablesize').text("Table Size: " + vv.length);
    $('#btnExport').prop('disabled', false);
}

/**
 * Reload logs from server with date and filter
 * @param {String} APIURL API URL endpoint , default "Log/"
 * @param {String} date date in format dd-mm-yyyy
 * @param {String} filter log filter text
 */
function reloadLogs(APIURL = "Log/", date, filter) {
    const params = new URLSearchParams({
        date: date,
        filter: filter
    })
    window.logdata = [];
    fetchAPI(APIURL + "List?" + params.toString(), "GET", {}, null, (okdata) => {
        if (Array.isArray(okdata)) {
            window.logdata.push(...okdata);
            fill_logtablebody(window.logdata);
        }
    }, (errdata) => {
        alert("Error loading logs : " + errdata.message);
    });
}

$(document).ready(function () {
    console.log("log.js ready");
    let selectedlogdate = "";
    let logfilter = "";
    let APIURL = "Log/";
    $('#logtablebody').empty();


    if (!$('#logdate').val()) {
        const today = new Date();
        const dd = String(today.getDate()).padStart(2, '0');
        const mm = String(today.getMonth() + 1).padStart(2, '0');
        const yyyy = today.getFullYear();
        $('#logdate').val(`${yyyy}-${mm}-${dd}`);
        selectedlogdate = `${dd}-${mm}-${yyyy}`;
        reloadLogs(APIURL, selectedlogdate, logfilter);
    }
    $('#logdate').off('change').on('change', function () {
        const selected = $(this).val();
        if (selected) {
            const [year, month, day] = selected.split('-');
            selectedlogdate = `${day}-${month}-${year}`;
            reloadLogs(APIURL, selectedlogdate, logfilter);
        }
    });

    $('#searchfilter').off('input').on('input', function () {
        logfilter = $(this).val();
        reloadLogs(APIURL, selectedlogdate, logfilter);
    });
    $('#btnExport').off('click').on('click', function () {
        DoExport(APIURL, "log.xlsx", { date: selectedlogdate, filter: logfilter });
    });
});