// How often to query the server?
const REFRESH_INTERVAL_SEC = 60 * 10;
// Last time the alerts list was updated on display.
let lastUpdateTime;

// Storage for the alert data that the server gives us.
let alerts = [];

// Load alerts and populate the table.
function loadAlerts() {
    $.ajax({url: '/api/v2/alerts' + buildQueryString(), dataType: 'json', headers: getCredentialHeaders(), success: function (jsonData) {
        // Store last updated time
        lastUpdateTime = moment.utc();
        updateRefreshDisplay();
        // Store data
        alerts = jsonData;
        // Update table
        updateTable();
    }});
}

// Build a query string for the API, based on the filters that the user has selected.
function buildQueryString() {
    let str = "?";
    ["dx_continent", "source"].forEach(fn => {
        if (!allFilterOptionsSelected(fn)) {
            str = str + getQueryStringFor(fn) + "&";
        }
    });
    str = str + "limit=" + $("#alerts_to_fetch option:selected").val();
    const maxDur = $("#max-duration option:selected").val();
    if (maxDur !== "9999999999") {
        str = str + "&max_duration=" + maxDur;
    }
    if ($("#dxpeditions_skip_max_duration_check")[0].checked) {
        str = str + "&dxpeditions_skip_max_duration_check=true";
    }
    return str;
}

// Update the alerts table
function updateTable() {
    // Use local time instead of UTC?
    const useLocalTime = $("#timeZone")[0].value === "local";

    // Table data toggles
    const showStartTime = $("#tableShowStartTime")[0].checked;
    const showEndTime = $("#tableShowEndTime")[0].checked;
    const showDX = $("#tableShowDX")[0].checked;
    const showFreqsModes = $("#tableShowFreqsModes")[0].checked;
    const showComment = $("#tableShowComment")[0].checked;
    const showSource = $("#tableShowSource")[0].checked;
    const showRef = $("#tableShowRef")[0].checked;

    // Populate table with headers
    let table = $("#table");
    table.find('thead tr').empty();
    if (showStartTime) {
        table.find('thead tr').append(`<th class="bg-primary-subtle">${useLocalTime ? "Start&nbsp;(Local)" : "Start&nbsp;UTC"}</th>`);
    }
    if (showEndTime) {
        table.find('thead tr').append(`<th class="bg-primary-subtle">${useLocalTime ? "End&nbsp;(Local)" : "End&nbsp;UTC"}</th>`);
    }
    if (showDX) {
        table.find('thead tr').append(`<th class="bg-primary-subtle">DX</th>`);
    }
    if (showFreqsModes) {
        table.find('thead tr').append(`<th class='bg-primary-subtle hideonmobile'>Freq<span class='hideonmobile'>uencie</span>s & Modes</th>`);
    }
    if (showComment) {
        table.find('thead tr').append(`<th class='bg-primary-subtle hideonmobile'>Comment</th>`);
    }
    if (showSource) {
        table.find('thead tr').append(`<th class='bg-primary-subtle hideonmobile'>Source</th>`);
    }
    if (showRef) {
        table.find('thead tr').append(`<th class='bg-primary-subtle hideonmobile'>Ref.</th>`);
    }

    table.find('tbody').empty();

    // Split alerts into three types, each of which will get its own table header: On now, next 24h, and later. "On now"
    // is considered to be events with an end_time where start<now<end, or events with no end time that started in the
    // last hour.
    const onNow = alerts.filter(a => (a["end_time"] != null && a["end_time"] !== 0 && moment.unix(a["end_time"]).utc().isSameOrAfter() && moment.unix(a["start_time"]).utc().isBefore())
        || ((a["end_time"] == null || a["end_time"] === 0) && moment.unix(a["start_time"]).utc().add(1, 'hours').isSameOrAfter() && moment.unix(a["start_time"]).utc().isBefore()));
    const next24h = alerts.filter(a => moment.unix(a["start_time"]).utc().isSameOrAfter() && moment.unix(a["start_time"]).utc().subtract(24, 'hours').isBefore());
    const later = alerts.filter(a => moment.unix(a["start_time"]).utc().subtract(24, 'hours').isSameOrAfter());

    if (onNow.length > 0) {
        table.find('tbody').append('<tr><td colspan="100" class="bg-primary-subtle" style="text-align:center;">On Now</td></tr>');
        addAlertRowsToTable(table.find('tbody'), onNow);
    }

    if (next24h.length > 0) {
        table.find('tbody').append('<tr><td colspan="100" class="bg-primary-subtle" style="text-align:center;">Starting within 24 hours</td></tr>');
        addAlertRowsToTable(table.find('tbody'), next24h);
    }

    if (later.length > 0) {
        table.find('tbody').append('<tr><td colspan="100" class="bg-primary-subtle" style="text-align:center;">Starting later </td></tr>');
        addAlertRowsToTable(table.find('tbody'), later);
    }

    if (onNow.length === 0 && next24h.length === 0 && later.length === 0) {
        table.find('tbody').append('<tr class="bg-danger-subtle"><td colspan="100" style="text-align:center;">No alerts match your filters.</td></tr>');
    }
}

// Add a row to tbody for each alert in the provided list
function addAlertRowsToTable(tbody, alerts) {
    let count = 0;
    alerts.forEach(a => {
        // Create row
        let $tr = $('<tr>');

        // Apply striping to the table. We can't just use Bootstrap's table-striped class because we have all sorts of
        // extra faff to deal with, like the mobile view having extra rows, and the On Now / Next 24h / Later banners
        // which cause the table-striped colouring to go awry.
        if (count % 2 === 1) {
            $tr.addClass("table-active");
        }

        // Use local time instead of UTC?
        const useLocalTime = $("#timeZone")[0].value === "local";

        // Table data toggles
        const showStartTime = $("#tableShowStartTime")[0].checked;
        const showEndTime = $("#tableShowEndTime")[0].checked;
        const showDX = $("#tableShowDX")[0].checked;
        const showFreqsModes = $("#tableShowFreqsModes")[0].checked;
        const showComment = $("#tableShowComment")[0].checked;
        const showSource = $("#tableShowSource")[0].checked;
        const showRef = $("#tableShowRef")[0].checked;

        // Get times for the alert, and convert to local time if necessary.
        const start_time_utc = moment.unix(a["start_time"]).utc();
        const start_time_local = start_time_utc.clone().local();
        const start_time = useLocalTime ? start_time_local : start_time_utc;
        const end_time_utc = moment.unix(a["end_time"]).utc();
        const end_time_local = end_time_utc.clone().local();
        const end_time = useLocalTime ? end_time_local : end_time_utc;

        // Format the times for display. Start time is displayed as e.g. 7 Oct 12:34 unless the time is in a
        // different year to the current year, in which case the year is inserted between month and hour.
        // If the time is set to local not UTC, and the date in local time is "today", we display that instead.
        // End time is displayed the same as above, except if the end date is the same as the start date, in which case
        // just e.g. 23:45 is used.
        // Overriding all of that, if the start time is 00:00 and the end time is 23:59 when considered in UTC, the
        // hours and minutes are stripped out from the display, as we assume the server is just giving us full days.
        // Finally, if there is no end date set, "---" is displayed.
        const whole_days = start_time_utc.format("HH:mm") === "00:00" &&
            (end_time_utc === 0 || end_time_utc.format("HH:mm") === "23:59");
        const hours_minutes_format = whole_days ? "" : " HH:mm";
        let start_time_formatted = start_time.format("D MMM" + hours_minutes_format);
        if (start_time.format("YYYY") !== moment().format("YYYY")) {
            start_time_formatted = start_time.format("D MMM YYYY" + hours_minutes_format);
        } else if (useLocalTime && start_time.format("D MMM YYYY") === moment().format("D MMM YYYY")) {
            start_time_formatted = start_time.format("[Today]" + hours_minutes_format);
        }
        let end_time_formatted = "---";
        if (end_time_utc > 0 && end_time != null) {
            end_time_formatted = whole_days ? start_time_formatted : end_time.format("HH:mm");
            if (end_time.format("D MMM") !== start_time.format("D MMM")) {
                if (end_time.format("YYYY") !== moment().format("YYYY")) {
                    end_time_formatted = end_time.format("D MMM YYYY" + hours_minutes_format);
                } else if (useLocalTime && end_time.format("D MMM YYYY") === moment().format("D MMM YYYY")) {
                    end_time_formatted = end_time.format("[Today]" + hours_minutes_format);
                } else {
                    end_time_formatted = end_time.format("D MMM" + hours_minutes_format);
                }
            }
        }

        // Format dx country
        let dx_country = a["dx_country"];
        if (dx_country == null) {
            dx_country = "Unknown or not a country"
        }

        // Format DX flag
        let dx_flag = "<i class='fa-solid fa-globe-africa'></i>";
        if (a["dx_dxcc_id"] && a["dx_dxcc_id"] != null && a["dx_dxcc_id"] !== 0) {
            dx_flag = `<img src="static/img/flags/${a['dx_dxcc_id']}.png" class="flag" width="24" alt="${dx_country}" title="${dx_country}"/>`;
        }

        // Format dx calls
        let dx_calls_html = "";
        if (a["dx_calls"] != null) {
            dx_calls_html = a["dx_calls"].map(call => `<a class='dx-link' href='https://qrz.com/db/${call}' target='_new'>${call}</a>`).join(", ");
        }

        // Format DXpedition country
        let dx_country_html = "";
        if (a["is_dxpedition"] === true && a["dx_country"] != null && a["dx_country"] !== "") {
            dx_country_html = `<br/>${a["dx_country"]}`;
        }

        // Format freqs & modes
        let freqsModesText = "";
        if (a["freqs_modes"] != null) {
            freqsModesText = escapeHtml(a["freqs_modes"]);
        }

        // Format comment
        let commentText = "";
        if (a["comment"] != null) {
            commentText = escapeHtml(a["comment"]);
        }

        // Sig or fallback to source
        let sigSourceText = a["source"];
        if (a["sig"]) {
            sigSourceText = a["sig"];
        }

        // Format sig_refs
        let sig_refs = "";
        if (a["sig_refs"] != null) {
            const items = [];
            for (let i = 0; i < a["sig_refs"].length; i++) {
                if (a["sig_refs"][i]["url"] != null) {
                    items[i] = `<a href='${encodeURI(a["sig_refs"][i]["url"])}' title='${escapeHtml(a["sig_refs"][i]["name"])}' target='_new' class='sig-ref-link'>${escapeHtml(a["sig_refs"][i]["id"])}</a>`
                } else {
                    items[i] = `${escapeHtml(a["sig_refs"][i]["id"])}`
                }
            }
            sig_refs = items.join(", ");
        }

        // Populate the row
        if (showStartTime) {
            $tr.append(`<td class='nowrap'>${start_time_formatted}</td>`);
        }
        if (showEndTime) {
            $tr.append(`<td class='nowrap'>${end_time_formatted}</td>`);
        }
        if (showDX) {
            $tr.append(`<td class='nowrap'><span class='flag-wrapper hideonmobile' title='${dx_country}'>${dx_flag}</span>${dx_calls_html}${dx_country_html}</td>`);
        }
        if (showFreqsModes) {
            $tr.append(`<td class='hideonmobile'>${freqsModesText}</td>`);
        }
        if (showComment) {
            $tr.append(`<td class='hideonmobile'>${commentText}</td>`);
        }
        if (showSource) {
            $tr.append(`<td class='nowrap hideonmobile'><span class='icon-wrapper'><i class='fa-solid ${sigToIcon(a["sig"], "fa-globe-africa")}'></i></span> ${sigSourceText}</td>`);
        }
        if (showRef) {
            $tr.append(`<td class='hideonmobile'>${sig_refs}</td>`);
        }
        tbody.append($tr);

        // Second row for mobile view only, containing source, ref, freqs/modes & comment
        const $tr2 = $("<tr class='hidenotonmobile'>");
        if (count % 2 === 1) {
            $tr2.addClass("table-active");
        }
        const $td2 = $("<td colspan='100'>");
        if (showSource) {
            $td2.append(`<span class='icon-wrapper'><i class='fa-solid ${sigToIcon(a["sig"], "fa-globe-africa")}'></i></span> `);
        }
        if (showRef) {
            $td2.append(`${sig_refs} `);
        }
        if (showFreqsModes) {
            $td2.append(`${freqsModesText} `);
        }
        if (showComment) {
            $td2.append(`<br/>${commentText} `);
        }
        $tr2.append($td2);
        tbody.append($tr2);

        count++;
    });
}

// Load server options. Once a successful callback is made from this, we then query alerts.
function loadOptions() {
    $.getJSON('/api/v2/options', function (jsonData) {
        // Store options
        options = jsonData;

        // Populate the filters panel
        generateMultiToggleFilterCard("#dx_continent_options", "dx_continent", options["continents"]);
        generateMultiToggleFilterCard("#source-options", "source", options["alert_providers"]);

        // Load URL params. These may select things from the various filter & display options, so the function needs
        // to be called after these are set up, but if the URL params ask for "embedded mode", this will suppress
        // loading settings, so this needs to be called before that.
        loadURLParams();

        // Load filters from settings storage
        loadSettings();
        setColorScheme($("#color_scheme option:selected").val());

        // Load alerts and set up the timer
        loadAlerts();
        setInterval(loadAlerts, REFRESH_INTERVAL_SEC * 1000);
    });
}

// Method called when any filter is changed to reload the alerts and persist the filter settings.
function filtersUpdated() {
    loadAlerts();
    saveSettings();
}

// Update the refresh timing display
function updateRefreshDisplay() {
    if (lastUpdateTime != null) {
        let secSinceUpdate = moment.duration(moment().diff(lastUpdateTime)).asSeconds();
        let count = REFRESH_INTERVAL_SEC;
        let updatingString = "Updating..."
        if (secSinceUpdate < REFRESH_INTERVAL_SEC) {
            count = REFRESH_INTERVAL_SEC - secSinceUpdate;
            let number;
            if (count <= 60) {
                number = count.toFixed(0);
                updatingString = "<span class='nowrap'>Updating in " + number + " second" + (number !== "1" ? "s" : "") + ".</span>";
            } else {
                number = Math.round(count / 60.0).toFixed(0);
                updatingString = "<span class='nowrap'>Updating in " + number + " minute" + (number !== "1" ? "s" : "") + ".</span>";
            }
        }
        $("#timing-container").html("Last updated at " + lastUpdateTime.format('HH:mm') + " UTC. " + updatingString);
    }
}

// Startup
$(document).ready(function () {
    // Call loadOptions(), this will then trigger loading alerts and setting up timers.
    loadOptions();
    // Update the refresh timing display every second
    setInterval(updateRefreshDisplay, 1000);
});

// Reload alerts on becoming visible. This forces a refresh when used as a PWA and the user switches back to the PWA
// after some time has passed with it in the background.
addEventListener("visibilitychange", () => {
    if (!document.hidden) {
        loadAlerts();
    }
});