//declare variables for gauges and charts, defining options as per the plugin documentation
var temp_gauge = new JustGage({
    id: 'temp_gauge',
    value: 0,
    min: 10,
    max: 50,
    decimals: 2,
    width: 222,
    height: 150,
    symbol: ' °C',
    showInnerShadow: true,
    levelColors: ['#3300ff', '#fff200', '#ff0008'],
    customSectors: {
        percents: false,
        ranges: [{
            color : "#33ff00",
            lo : 20,
            hi : 25.5
        }]
    }
});

var hum_gauge = new JustGage({
    id: "hum_gauge",
    value: 0,
    min: 0,
    max: 100,
    decimals: 2,
    width: 222,
    height: 150,
    symbol: ' %',
    showInnerShadow: true,
    customSectors: {
        percents: false,
        ranges: [{
            color : "#33ff00",
            lo : 30,
            hi : 60
        }]
    }
});

var pres_gauge = new JustGage({
    id: "pres_gauge",
    value: 0,
    min: 900,
    max: 1050,
    decimals: 0,
    width: 222,
    height: 150,
    symbol: ' hPa',
    showInnerShadow: true,
    noGradient: true,
    customSectors: {
        percents: true,
        ranges: [{
            color : "#2200ff",
            lo : 0,
            hi : 100
        }]
    }
});

var co2_gauge = new JustGage({
    id: "co2_gauge",
    value: 0,
    min: 300,
    max: 5000,
    decimals: 0,
    width: 222,
    height: 150,
    symbol: ' ppm',
    showInnerShadow: true,
    levelColors: ['#33ff00', '#ffff00', '#ff8800', '#ff0008']
});

Chart.defaults.global.responsive = false;
var nan=NaN;

var tempChartData = {
    labels : [],
    datasets : [{
        label: 'Temperature',
        fill: true,
        lineTension: 0.1,
        backgroundColor: "rgba(75,192,192,0.4)",
        borderColor: "rgba(75,192,192,1)",
        borderCapStyle: 'butt',
        borderDash: [],
        borderDashOffset: 0.0,
        borderJoinStyle: 'miter',
        pointBorderColor: "rgba(75,192,192,1)",
        pointBackgroundColor: "#fff",
        pointBorderWidth: 1,
        pointHoverRadius: 5,
        pointHoverBackgroundColor: "rgba(75,192,192,1)",
        pointHoverBorderColor: "rgba(220,220,220,1)",
        pointHoverBorderWidth: 2,
        pointRadius: 1,
        pointHitRadius: 10,
        showLine: true,
        spanGaps: false,
        data : []
    }]
};

var tempChartSettings = {
    type : 'line',
    data : tempChartData,
    options : {
        legend: {
            display: false
        },
        scales : {
            xAxes : [{
                distribution: 'series',
                ticks: {
                    autoSkip: true,
                    maxTicksLimit: 20,
                },
                type: 'time',
                source: 'auto'
            }]
        }
    }
};

var humChartData = {
    labels : [],
    datasets : [{
        label: 'Humidity',
        fill: true,
        lineTension: 0.1,
        backgroundColor: "rgba(136,77,255,0.4)",
        borderColor: "rgba(136,77,255,1)",
        borderCapStyle: 'butt',
        borderDash: [],
        borderDashOffset: 0.0,
        borderJoinStyle: 'miter',
        pointBorderColor: "rgba(136,77,255,1)",
        pointBackgroundColor: "#fff",
        pointBorderWidth: 1,
        pointHoverRadius: 5,
        pointHoverBackgroundColor: "rgba(136,77,255,1)",
        pointHoverBorderColor: "rgba(220,220,220,1)",
        pointHoverBorderWidth: 2,
        pointRadius: 1,
        pointHitRadius: 10,
        data : [],
        spanGaps: false,
    }]
};

var humChartSettings = {
    type : 'line',
    showLines: false,
    data : humChartData,
    options : {
        legend: {
            display: false
        },
        scales : {
            xAxes : [{
                distribution: 'series',
                ticks: {
                    autoSkip: true,
                    maxTicksLimit: 20,
                },
                type: 'time',
                source: 'auto'
            }]
        }
    }
};

var co2ChartData = {
    labels : [],
    datasets : [{
        label: 'CO2 concentration',
        fill: true,
        lineTension: 0.1,
        backgroundColor: "rgba(0,128,43,0.4)",
        borderColor: "rgba(0,128,43,1)",
        borderCapStyle: 'butt',
        borderDash: [],
        borderDashOffset: 0.0,
        borderJoinStyle: 'miter',
        pointBorderColor: "rgba(0,128,43,1)",
        pointBackgroundColor: "#fff",
        pointBorderWidth: 1,
        pointHoverRadius: 5,
        pointHoverBackgroundColor: "rgba(0,128,43,1)",
        pointHoverBorderColor: "rgba(220,220,220,1)",
        pointHoverBorderWidth: 2,
        pointRadius: 1,
        pointHitRadius: 10,
        data : [],
        spanGaps: false,
    }]
};

var co2ChartSettings = {
    type : 'line',
    showLines: false,
    data : co2ChartData,
    options : {
        legend: {
            display: false
        },
        scales : {
            xAxes : [{
                distribution: 'series',
                ticks: {
                    autoSkip: true,
                    maxTicksLimit: 20,
                },
                type: 'time',
                source: 'auto'
            }],
            yAxes: [{
                ticks: {
                    min: 300,
                }
            }]
        }
    }
};

var multiChartData = {
    labels : [],
    datasets : [{
        label: 'Temperature',
        fill: true,
        lineTension: 0.1,
        backgroundColor: "rgba(75,192,192,0.4)",
        borderColor: "rgba(75,192,192,1)",
        borderCapStyle: 'butt',
        borderDash: [],
        borderDashOffset: 0.0,
        borderJoinStyle: 'miter',
        pointBorderColor: "rgba(75,192,192,1)",
        pointBackgroundColor: "#fff",
        pointBorderWidth: 1,
        pointHoverRadius: 5,
        pointHoverBackgroundColor: "rgba(75,192,192,1)",
        pointHoverBorderColor: "rgba(220,220,220,1)",
        pointHoverBorderWidth: 2,
        pointRadius: 1,
        pointHitRadius: 10,
        data : [],
        spanGaps: false,
    }, {
        label: 'Humidity',
        fill: true,
        lineTension: 0.1,
        backgroundColor: "rgba(136,77,255,0.4)",
        borderColor: "rgba(136,77,255,1)",
        borderCapStyle: 'butt',
        borderDash: [],
        borderDashOffset: 0.0,
        borderJoinStyle: 'miter',
        pointBorderColor: "rgba(136,77,255,1)",
        pointBackgroundColor: "#fff",
        pointBorderWidth: 1,
        pointHoverRadius: 5,
        pointHoverBackgroundColor: "rgba(136,77,255,1)",
        pointHoverBorderColor: "rgba(220,220,220,1)",
        pointHoverBorderWidth: 2,
        pointRadius: 1,
        pointHitRadius: 10,
        data : [],
        spanGaps: false,
    }]
};

var multiChartSettings = {
    type : 'line',
    showLines: false,
    data : multiChartData,
    options : {
        scales : {
            xAxes : [{
                distribution: 'series',
                ticks: {
                    autoSkip: true,
                    maxTicksLimit: 20,
                },
                type: 'time',
                source: 'auto'
            }],
            yAxes : [{
                ticks: {
                    min: 10
                }
            }]
        }
    }
};

//instantiate chart objects with defined options
var ctx = document.getElementById('tempchart').getContext("2d");
var tempChart = new Chart(ctx,tempChartSettings);
var ctx2 = document.getElementById('humchart').getContext("2d");
var humChart = new Chart(ctx2,humChartSettings);
var ctx3 = document.getElementById('co2chart').getContext("2d");
var co2Chart = new Chart(ctx3,co2ChartSettings);
var ctx4 = document.getElementById('multichart').getContext("2d");
var multiChart = new Chart(ctx4,multiChartSettings);
//function to clear chart datasets without redrawing
function clearChartData() {
    tempChart.data.datasets[0].data = [];
    tempChart.data.labels = [];
    humChart.data.datasets[0].data = [];
    humChart.data.labels = [];
    co2Chart.data.datasets[0].data = [];
    co2Chart.data.labels = [];
    multiChart.data.datasets[0].data = [];
    multiChart.data.datasets[1].data = [];
    multiChart.data.labels = [];
};
//function to remove last value of chart dataset, used to create a "scrolling" effect as new values come in
function trimChartData() {
    tempChart.data.datasets[0].data.shift();
    tempChart.data.labels.shift();
    humChart.data.datasets[0].data.shift();
    humChart.data.labels.shift();
    co2Chart.data.datasets[0].data.shift();
    co2Chart.data.labels.shift();
    multiChart.data.datasets[0].data.shift();
    multiChart.data.datasets[1].data.shift();
    multiChart.data.labels.shift();
}
//function to update the chart datasets with data from the database
function updateChart(dbdata) {
    $.each(dbdata['temp'], function(key, value) {
        tempChart.data.labels.push(key);
        humChart.data.labels.push(key);
        co2Chart.data.labels.push(key);
        multiChart.data.labels.push(key);
        tempChart.data.datasets[0].data.push(value);
        multiChart.data.datasets[0].data.push(value);
    });
    $.each(dbdata['hum'], function(key, value){
        humChart.data.datasets[0].data.push(value);
        multiChart.data.datasets[1].data.push(value);
    });
    $.each(dbdata['co2'], function(key, value){
        co2Chart.data.datasets[0].data.push(value);
    });

    tempChart.update();
    humChart.update();
    co2Chart.update();
    multiChart.update();
};
//function to update the gauges
function updateGauge(dbdata) {
    for(var key in dbdata.temp){};
    temp_gauge.refresh(dbdata.temp[key]);
    hum_gauge.refresh(dbdata.hum[key]);
    pres_gauge.refresh(dbdata.pres[key]);
    co2_gauge.refresh(dbdata.co2[key]);
    $('#timestamp').text(key);
};
//ajax data fetching function
function getServerData(samples) {
    return $.ajax({
        type: 'POST',
        url: '/api/getdata',
        data: {'samples' : samples },
        dataType: 'json',
        success: console.log("requested db data"),
    });
};
//the main function, updates the values based on the device status, run on a timer
function getStatusAndDecide() {
    var statusData = $.ajax ({
        type: 'GET',
        url: '/api/heartbeat',
        data: {},
        dataType: 'json',
        success: console.log("requested heartbeat data"),
    }).done(function (retdata) {
        if ( typeof getStatusAndDecide.statusWas === 'undefined' ) {
            getStatusAndDecide.statusWas = "dead";
        };
        if (retdata.status == "alive" && getStatusAndDecide.statusWas == "alive") {
            $.when(getServerData(1)).done(function(retdata) {
                updateChart(retdata);
                updateGauge(retdata);
            });
            trimChartData();
            getStatusAndDecide.statusWas = "alive";
        }
        else if (retdata.status == "alive" && getStatusAndDecide.statusWas == "dead") {
            $('#footer_text').text("Live update enabled. (Data might be delayed up to a minute)");
            clearChartData();
            $.when(getServerData($('input[name=samples]').val())).done(function(retdata) {
                updateChart(retdata);
                updateGauge(retdata);
            });
            getStatusAndDecide.statusWas = "alive";
        }
        else if (retdata.status == "dead" && getStatusAndDecide.statusWas == "alive") {
            $('#footer_text').text("Source not online, live update disabled. Showing latest available data.");
            getStatusAndDecide.statusWas = "dead";
        }
        else if (retdata.status == "dead" && getStatusAndDecide.statusWas == "dead") {
            getStatusAndDecide.statusWas == "dead";
        }
        else {
            location.reload(forceGet);
        }
    });
};
//functions run after clicking the refresh button
$('#refresh').click(function() {
    console.log("refreshing all");
    clearChartData();
    $.when(getServerData($('input[name=samples]').val())).done(function(retdata) {
        updateChart(retdata);
        updateGauge(retdata);
    });
});
//functions run after choosing sample amount from the gui
$('#sample_select_form').submit(function (f) {
    f.preventDefault();
    console.log("selected range from form");
    clearChartData();
    $.when(getServerData($('input[name=samples]').val())).done(function(retdata) {
        updateChart(retdata);
        updateGauge(retdata);
    });
});
//function run on page load, fetches and dislpays the latest data
$(document).ready(function() {
    $.when(getServerData($('input[name=samples]').val())).done(function(retdata) {
        if (retdata.status == "alive") {
            $('#footer_text').text("Live update enabled. (Data might be delayed up to a minute)");
        }
        else if (retdata.status == "dead") {
            $('#footer_text').text("Source not online, live update disabled. Showing latest available data.");
        }
        updateChart(retdata);
        updateGauge(retdata);
    });
});
//90 second timer to refresh contents
setInterval("getStatusAndDecide()", 90000);
