// Load server status
function loadStatus() {
    $.getJSON('/api/v1/status', function(jsonData) {
        $("#status-container").empty();
        $("#status-container").append(generateStatusCard("Server Information", [
            `Software Version: ${jsonData["software-version"]}`,
            `Server Owner Callsign: ${jsonData["server-owner-callsign"]}`,
            `Server up since: ${moment().subtract(jsonData["uptime"], 'seconds').fromNow()}`,
            `Memory Use: ${jsonData["mem_use_mb"]} MB`,
            `Total Spots: ${jsonData["num_spots"]}`,
            `Total Alerts: ${jsonData["num_alerts"]}`
        ]));
        $("#status-container").append(generateStatusCard("Web Server", [
            `Status: ${jsonData["webserver"]["status"]}`,
            `Last API Access: ${moment.unix(jsonData["webserver"]["last_api_access"]).utc().fromNow()}`,
            `Last Page Access: ${moment.unix(jsonData["webserver"]["last_page_access"]).utc().fromNow()}`
        ]));
        $("#status-container").append(generateStatusCard("Cleanup Service", [
            `Status: ${jsonData["cleanup"]["status"]}`,
            `Last Ran: ${moment.unix(jsonData["cleanup"]["last_ran"]).utc().fromNow()}`
        ]));
        jsonData["spot_providers"].forEach(p => {
            $("#status-container").append(generateStatusCard("Spot Provider: " + p["name"], [
                `Status: ${p["status"]}`,
                `Last Updated: ${(p["enabled"] && p["last_updated"] > 0) ? moment.unix(p["last_updated"]).utc().fromNow() : "N/A"}`,
                `Latest Spot: ${(p["enabled"] && p["last_spot"] > 0) ? moment.unix(p["last_spot"]).utc().fromNow() : "N/A"}`
            ]));
        });
        jsonData["alert_providers"].forEach(p => {
            $("#status-container").append(generateStatusCard("Alert Provider: " + p["name"], [
                `Status: ${p["status"]}`,
                `Last Updated: ${(p["enabled"] && p["last_updated"] > 0) ? moment.unix(p["last_updated"]).utc().fromNow() : "N/A"}`
            ]));
        });
    });
}

// Generate a status card
function generateStatusCard(title, textLines) {
    let $col = $("<div class='col'>");
    let $card = $("<div class='card'>");
    let $card_body = $("<div class='card-body'>");
    $card_body.append(`<h5 class='card-title'>${title}</h5>`);
    $card_body.append(`<p class='card-text'>${textLines.join("<br/>")}</p>`);
    $card.append($card_body);
    $col.append($card);
    return $col;
}

// Startup
$(document).ready(function() {
    loadStatus();
});