{% extends "layout.jinja2" %}

{% block content %}
<div class="content">
    <div class="row">
        <div class="col-xs-12">
            <h2>Latest Tag Values: {{tagname}}</h2>
        </div>
    </div>
    <div class="row">
        <div class="col-xs-12">
            <canvas id="myChart" height="120"></canvas>
        </div>
    </div>
</div>
<meta id="tag_data" data-name="{{tag_values}}">
<script type="text/javascript" src="{{request.static_url('pocwww:static/linechart.js')}}"></script>
<script>
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'];

var graph_data = [] ;
// var data = $('#tag_data').data().name.replace(/'/g, '"');
// var json_data = JSON.parse(data);

function drawSingleGraph(data){
    console.log(data);
    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 < data.length; i++){
        for(var j = 0; j < lines.length; j++){
            var tagname = lines[j]
            graph_data[lines.indexOf(tagname)].data.push({
                x: data[i].timestamp,
                y: data[i][tagname]
            });
        }
    }

    var scatterChart = new Chart(ctx, {
        type: 'line',
        data: {
            datasets: graph_data
        },
        options: {
            scales: {
                xAxes: [{
                    type: 'time',
                    position: 'bottom'
                }]
            }
        }
    });
}

var urlparts = decodeURIComponent(window.location).split("/").slice(3)
var endD = new Date();
var end = endD.toISOString();
var dummyDate = new Date();
var startD = new Date(dummyDate.setDate(endD.getDate() - 2));
var start = startD.toISOString();

if(urlparts.length >= 5){
    start = urlparts[3];
    end = urlparts[4];
}

$.ajax({
    dataType: 'json',
    url:"/json/values/tag/{{tagname}}/daterange",
    success: drawSlider
});

$.ajax({
    dataType: 'json',
    url:"/json/values/tag/{{tagname}}/between/" + start + "/" + end,
    success: drawChart
});

</script>
{% endblock content %}
