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

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) {
        var jsDate = new Date(ping.date);
        //res.date.push(ping.date);
        res.min.push({ x: jsDate, y: ping.min });
        res.avg.push({ x: jsDate, y: ping.avg });
        res.max.push({ x: jsDate, y: ping.max });
        res.failures.push({ x: jsDate, y: ping.failures });
    }
    return res;
}

async function activateChart(id) {
    var chartDiv = $("#chartContainer");
    var chartId = "chart_" + id;
    var charts = chartDiv.children("canvas");
    for (let chart of charts) {
        var thisId = $(chart).attr('id');
        if (thisId == chartId) {
            $(chart).show();
        } else {
            $(chart).hide();
        }
        console.log(chart);
    }
}

async function prepareChart(host) {
    var buttonDiv = $("#chartContainerButtons");
    var chartDiv = $("#chartContainer");
    var chartId = "chart_" + host.hostId;
    var canvas = $("<canvas>", { id: chartId, width: 400, height: 200 }).appendTo(chartDiv).hide();
    $("<button>",{ class: "btn btn-primary"}).appendTo(buttonDiv).text(host.name).click(async () => {
        await activateChart(host.hostId);
        activeChart = host.hostId;
    });
    return canvas[0];
}

async function updateGraphs() {
    var chartDiv = $("#chartContainer");
    chartDiv.empty();
    charts = [];
    var buttonDiv = $("#chartContainerButtons");
    buttonDiv.empty();
    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 chartElement = await prepareChart(host);
        console.log("chartElement: ", chartElement);
        var val = await transformChartData(await fetchPings(host.hostId, start, end));
        var ctx = chartElement.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
                    },
                    {
                        label: 'fail',
                        //type: 'bar',
                        backgroundColor: 'rgba(0, 0, 0, 0.3)',
                        borderColor: 'rgb(0, 0, 0)',
                        yAxisID: "y-loss",
                        data: val.failures
                    },
                ]
            },
            options: {
                title: {
                    display: true,
                    text: host.name
                },
                //
                // Performance optimizations
                //
                animation: {
                    duration: 0, // general animation time
                },
                hover: {
                    animationDuration: 0, // duration of animations when hovering an item
                },
                elements: {
                    line: {
                        tension: 0 // disables bezier curves
                    }
                },
                responsiveAnimationDuration: 0, // animation duration after a resize
                //
                // Performance optimizations
                //
                scales: {
                    xAxes: [{
                        type: 'time',
                        distribution: 'linear',
                        time: {
                            unit: 'hour'
                        }
                    }],
                    yAxes: [
                        {
                            id: "y-latency",
                            position: "left",
                            ticks: {
                                suggestedMin: 0,
                                suggestedMax: 100,
                                max: 200
                            }
                        },
                        {
                            id: "y-loss",
                            position: "right",
                            ticks: {
                                suggestedMin: 0,
                                suggestedMax: 5
                            }
                        },/*
                        {
                            id: "y-avg",
                            position: "left",
                            ticks: {
                                suggestedMin: 950,
                                suggestedMax: 1050
                            }
                        },
                        {
                            id: "y-max",
                            position: "right",
                            ticks: {
                                suggestedMin: 0,
                                suggestedMax: 100
                            }
                        },*/
                    ]
                }
            }
        });
    }
    activateChart(activeChart);
}

$('#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 ipv6 = $('#chkIPv6').prop('checked');
    var ping = $('#chkPing').prop('checked');
    var tcp = $('#chkPing').prop('checked');
    var host = {
        name: name,
        hostname: hostname,
        ipv6: ipv6,
        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
    });
};