var simple_color_scale = ["#e41a1c", "#377eb8", "#4daf4a", "#984ea3", "#ff7f00", "#ffff33", "#a65628", "#f781bf"];
var color_scale = ['#a6cee3','#1f78b4','#b2df8a','#33a02c','#fb9a99','#e31a1c','#fdbf6f','#ff7f00','#cab2d6','#6a3d9a','#ffff99','#b15928'];

function drawCards(data){
    var graph_data = [] ;
    var json_data = data.card;
    var surf = document.getElementById("surfacecard");
    var down = document.getElementById("downholecard");

    var surfaceCardData = [{
        label: 'Surface Card',
        fill: false,
        data: [],
        lineTension: 0.05,
        borderColor: color_scale[2],
        pointRadius: 2
    }];

    var downholeCardData = [{
        label: 'Downhole Card',
        fill: false,
        data: [],
        lineTension: 0.05,
        borderColor: color_scale[1],
        pointRadius: 2
    }];

    for (var i = 0; i < json_data['surface_position'].length; i++){
        surfaceCardData[0].data.push({
            x: json_data['surface_position'][i],
            y: json_data['surface_load'][i]
        });
    }

    for (var i = 0; i < json_data['downhole_position'].length; i++){
        downholeCardData[0].data.push({
            x: json_data['downhole_position'][i],
            y: json_data['downhole_load'][i]
        });
    }

    var surfaceChart = new Chart(surf, {
        type: 'line',
        responsive: true,
        data: {
            datasets: surfaceCardData
        },
        options: {
            scales: {
                xAxes: [{
                    type: 'linear',
                    position: 'bottom'
                }]
            },
            legend: {
                display: false
            }
        }
    });

    var downholeChart = new Chart(down, {
        type: 'line',
        responsive: true,
        data: {
            datasets: downholeCardData
        },
        options: {
            scales: {
                xAxes: [{
                    type: 'linear',
                    position: 'bottom'
                }]
            },
            legend: {
                display: false
            }
        }
    });
}

function drawChart(data){
    if (typeof(scatterChart) != "undefined"){
        console.log("Destroying existing chart");
        scatterChart.destroy();
    }
    var graph_data = [] ;
    var json_data = data.values;
    var ctx = document.getElementById("valueChart");
    for (var i = 0; i < json_data.length; i++){
        var newObj = {
            label: json_data[i].tagname,
            fill: false,
            data: [],
            lineTension: 0.05,
            borderColor: color_scale[i % color_scale.length],
            pointRadius: 2
        }
        for(var j = 0; j < json_data[i].timestamps.length; j++){
            newObj.data.push({
                x: json_data[i].timestamps[j],
                y: json_data[i].currentValues[j]
            });
        }
        graph_data.push(newObj);
    }
    scatterChart = new Chart(ctx, {
        type: 'line',
        responsive: true,
        data: {
            datasets: graph_data
        },
        options: {
            scales: {
                xAxes: [{
                    type: 'time',
                    position: 'bottom'
                }]
            },
            legend: {
                labels: {
                    boxWidth: 20
                }
            }
        }
    });
}

function drawSingleGraph(data){
    if (typeof(scatterChart) != "undefined"){
        console.log("Destroying existing chart");
        scatterChart.destroy();
    }
    var graph_data = [];
    var values = data.values;
    var ctx = document.getElementById("myChart");
    var lines = ["currentValue", "maxDailyValue", "minDailyValue", "dailyAverage", "dailyTotal"];
    for (var i = 0; i < lines.length; i++){
        var baseObj = {
            label: lines[i],
            fill: false,
            data: [],
            lineTension: 0.05,
            borderColor: color_scale[i % color_scale.length]
        }
        if (lines[i] == "dailyTotal"){
            baseObj['hidden'] = true;
        }
        graph_data.push(baseObj);
    }

    for(var i = 0; i < values.length; i++){
        for(var j = 0; j < lines.length; j++){
            var lineName = lines[j]
            graph_data[lines.indexOf(lineName)].data.push({
                x: values[i].timestamp,
                y: values[i][lineName]
            });
        }
    }
    scatterChart = new Chart(ctx, {
        type: 'line',
        data: {
            datasets: graph_data
        },
        options: {
            scales: {
                xAxes: [{
                    type: 'time',
                    position: 'bottom'
                }]
            }
        }
    });
}


function drawAllSlider(data){

    var date_min = new Date(Date.parse(data.first_date));
    var date_max = new Date(Date.parse(data.last_date));
    console.log(data);

    var min_val = date_min/1000;
    var max_val = date_max/1000;

    var endD = new Date();
    var dummyDate = new Date();
    var startD = new Date(dummyDate.setDate(endD.getDate() - 2));


    var start_date = startD/1000;
    $('#slider-start').html(startD.toString());
    if(start_date < min_val){
        start_date = min_val;
        $('#slider-start').html(date_min.toString());
    }

    var end_date = endD/1000;
    $('#slider-end').html(startD.toString());
    if(end_date > max_val){
        end_date = max_val;
        $('#slider-end').html(date_max.toString());
    }

    $("#slider-range").slider({
        range: true,
        min: min_val,
        max: max_val,
        step: 10,
        values: [start_date, end_date],
        slide: function (e, ui) {
            var dt_cur_from = new Date(ui.values[0]*1000); //.format("yyyy-mm-dd hh:ii:ss");
            $('#slider-start').html(dt_cur_from.toString());

            var dt_cur_to = new Date(ui.values[1]*1000); //.format("yyyy-mm-dd hh:ii:ss");
            $('#slider-end').html(dt_cur_to.toString());
        },
        stop: function(e, ui){
            var startD = new Date(ui.values[0]*1000);
            var endD = new Date(ui.values[1]*1000);
            $.ajax({
                dataType: 'json',
                url:"/json/values/between/" + startD.toISOString() + "/" + endD.toISOString(),
                success: drawChart
            });
        }
    });
}

function drawSingleSlider(data){

    var date_min = new Date(Date.parse(data.first_date));
    var date_max = new Date(Date.parse(data.last_date));
    console.log(data);
    var min_val = date_min/1000;
    var max_val = date_max/1000;

    var endD = new Date();
    var dummyDate = new Date();
    var startD = new Date(dummyDate.setDate(endD.getDate() - 2));


    var start_date = startD/1000;
    $('#slider-start').html(startD.toString());
    if(start_date < min_val){
        start_date = min_val;
        $('#slider-start').html(date_min.toString());
    }

    var end_date = endD/1000;
    $('#slider-end').html(startD.toString());
    if(end_date > max_val){
        end_date = max_val;
        $('#slider-end').html(date_max.toString());
    }

    $("#slider-range").slider({
        range: true,
        min: min_val,
        max: max_val,
        step: 10,
        values: [start_date, end_date],
        slide: function (e, ui) {
            var dt_cur_from = new Date(ui.values[0]*1000); //.format("yyyy-mm-dd hh:ii:ss");
            $('#slider-start').html(dt_cur_from.toString());

            var dt_cur_to = new Date(ui.values[1]*1000); //.format("yyyy-mm-dd hh:ii:ss");
            $('#slider-end').html(dt_cur_to.toString());
        },
        stop: function(e, ui){
            var startD = new Date(ui.values[0]*1000);
            var endD = new Date(ui.values[1]*1000);
            $.ajax({
                dataType: 'json',
                url: "/json/values/tag/" + tagName + "/between/" + startD.toISOString() + "/" + endD.toISOString(),
                success: drawSingleGraph
            });
        }
    });
}
