var hosts = [];
var charts = {};

async function createHost(host) {
    $.postJSON("/api/host", host).then((res, status) => {
        console.log("POSTED" + status, res);
        if (status === "success") {
            fetchHosts();
        }
    });
}

async function deleteHost(hostId) {
    var res = await $.ajax({
        url: "/api/host/" + hostId,
        type: "DELETE"
    });
    console.log("DELETED");
    fetchHosts();
}

async function fetchHosts() {
    var tbody = $("#tblHosts > tbody");
    tbody.empty();
    hosts = [];
    var res = await $.getJSON("/api/host");
    console.log("Got hosts: ", res);
    for (let host of res) {
        var row = $("<tr>",).appendTo(tbody);
        $("<td>").text(host.hostId).appendTo(row);
        $("<td>").text(host.name).appendTo(row);
        $("<td>").text(host.hostName).appendTo(row);
        $("<td>").text("Delete").click(() => {
            deleteHost(host.hostId);
            }).appendTo(row);
    }
    hosts = res;
    updateGraphs();
}

async function fetchPings(hostId, start, end) {
    var res = await $.getJSON("/api/host/" + hostId + "/pings/" + start + "/" + end);
    console.log("Fetched pings: ", res);
    return res;
}

async function transformChartData(pings) {
    var res = { date: [], min: [], avg: [], max: [], failures: []};
    for (let ping of pings) {
        res.date.push(ping.date);
        res.min.push(ping.min);
        res.avg.push(ping.avg);
        res.max.push(ping.max);
        res.failures.push(ping.failures);
    }
    return res;
}

async function updateGraphs() {
    var chartDiv = $("#charts");
    chartDiv.empty();
    charts = [];
    var pastMinutes = $("#inpHistoryPast").val();
    var start = Date.now() - pastMinutes * 60 * 1000;
    var end = Date.now();
    for (let host of hosts) {
        console.log("Appending ", host);
        var val = await transformChartData(await fetchPings(host.hostId, start, end));
        $("<canvas>", { id: "chart_" + host.hostId, width: 200, height: 200 }).appendTo(chartDiv);
        var ctx = document.getElementById('chart_' + host.hostId).getContext('2d');
        charts[host.hostId] = new Chart(ctx, {
            type: 'line',
            data: {
                labels: val.date,
                datasets: [
                    {
                        label: 'min',
                        backgroundColor: 'rgba(255, 99, 132, 0.3)',
                        borderColor: 'rgb(255, 99, 132)',
                        yAxisID: "y-latency",
                        data: val.min
                    },
                    {
                        label: 'avg',
                        backgroundColor: 'rgba(99, 255, 132, 0.3)',
                        borderColor: 'rgb(99, 255, 132)',
                        yAxisID: "y-latency",
                        data: val.avg
                    },
                    {
                        label: 'max',
                        backgroundColor: 'rgba(132, 99, 255, 0.3)',
                        borderColor: 'rgb(132, 99, 255)',
                        yAxisID: "y-latency",
                        data: val.max
                    },
                ]
            },
            options: {
                title: {
                    display: true,
                    text: host.name
                },
                scales: {
                    yAxes: [
                        {
                            id: "y-latency",
                            position: "left",
                            ticks: {
                                suggestedMin: 10,
                                suggestedMax: 40
                            }
                        },/*
                        {
                            id: "y-avg",
                            position: "left",
                            ticks: {
                                suggestedMin: 950,
                                suggestedMax: 1050
                            }
                        },
                        {
                            id: "y-max",
                            position: "right",
                            ticks: {
                                suggestedMin: 0,
                                suggestedMax: 100
                            }
                        },*/
                    ]
                }
            }
        });
    }
}

$('#btnDebug').click(async () => {
    console.log("DEBUG");
});

$("#frmHistory").submit((event) => {
    event.preventDefault();
    updateGraphs();
});

$("#frmHostAdd").submit((event) => {
    event.preventDefault();
    var name = $("#inpNameAdd").val();
    var hostname = $("#inpHostNameAdd").val();
    var ping = $('#chkPing').prop('checked')
    var tcp = $('#chkPing').prop('checked')
    var host = {
        name: name,
        hostname: hostname,
        ping: ping,
        tcp: tcp
    }
    createHost(host);
});

fetchHosts();

jQuery["postJSON"] = function (url, data, callback) {
    // shift arguments if data argument was omitted
    if (jQuery.isFunction(data)) {
        callback = data;
        data = undefined;
    }

    if (data) {
        if (typeof data === 'string') {
            data = JSON.stringify(data);
        }
    }

    return jQuery.ajax({
        url: url,
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: JSON.stringify(data),
        success: callback
    });
};