<div class='col-xs-12' style="padding-top: 1em; margin-bottom: 1em;">
    <div class="input-daterange input-group" id="datepicker">
        <input data-chartid="dynamicChart" id="fromDate" data-daysofhistory="30"  type="text" class="form-control" name="start">
        <span class="input-group-addon">to</span>
        <input class="form-control" data-chartid="dynamicChart" id="toDate" type="text"  name="end">
        <span class='input-group-btn'>
            <a href="#!" data-chartid="dynamicChart" data-otherchartids="statusTimeline" class="btn chart-update btn-theme">Run</a>
        </span>
    </div>
</div>

<div class='clearfix col-xs-12' style='height: 300px' id="dynamicChart" data-chart="dynamicchart" data-daysofhistory="30"  data-chartlabel="Data" data-ylabel="" data-xlabel="Date" data-units=""  data-channelnames="poc.go_kwh,poc.go_electricity_cost,poc.go_peak_load,poc.go_min_load,poc.go_average_spm,poc.go_production_calculated,poc.go_full_card_production,poc.go_polished_rod_hp,poc.go_lifting_cost,poc.go_fluid_above_pump,poc.go_pump_intake_pressure,poc.go_kwh_regen,poc.go_inflow_rate"></div>

<div class='col-xs-12' style='margin-top: 2em;'>
    <table class="table">
        <thead>
            <th>Date</th>
            <th>% Run</th>
            <th>kWh</th>
            <th>Electricity Cost</th>
            <th>Peak Load</th>
            <th>Min. Load</th>
            <th>Average SPM</th>
            <th>Production</th>
            <th>Full Card Production</th>
            <th>Polished Rod HP</th>
            <th>Lifting Cost</th>
            <th>Fluid Level</th>
            <th>Pump Intake Pressure</th>
            <th>kWh Regen</th>
            <th>Inflow Rate</th>
        </thead>

        <tbody id="output">
        </tbody>
        
    </table>
</div>


<style>
    .dynamic-chart-form {
        background-color: whiteSmoke;
        padding: 1em 0.5em;
        margin-top: 1em;
    }
</style>

<script>
    var tableData = {};
    var nodeID = <%= node.nodeId %>;
    var nodeType = '<%= node.nodetypeName %>';
    var channelData = {
        go_percent_run:               {name:<%= channels['poc.go_percent_run'].channelId %>,            values:[]},
        go_kwh:                       {name:<%= channels['poc.go_kwh'].channelId %>,                    values:[]},
        go_electricity_cost:          {name:<%= channels['poc.go_electricity_cost'].channelId %>,       values:[]},
        go_peak_load:                 {name:<%= channels['poc.go_peak_load'].channelId %>,              values:[]},
        go_min_load:                  {name:<%= channels['poc.go_min_load'].channelId %>,               values:[]},
        go_average_spm:               {name:<%= channels['poc.go_average_spm'].channelId %>,            values:[]},
        go_production_calculated:     {name:<%= channels['poc.go_production_calculated'].channelId %>,  values:[]},
        go_polished_rod_hp:           {name:<%= channels['poc.go_polished_rod_hp'].channelId %>,        values:[]},
        go_lifting_cost:              {name:<%= channels['poc.go_lifting_cost'].channelId %>,           values:[]},
        go_fluid_above_pump:          {name:<%= channels['poc.go_fluid_above_pump'].channelId %>,       values:[]},
        go_pump_intake_pressure:      {name:<%= channels['poc.go_pump_intake_pressure'].channelId %>,   values:[]},
        go_kwh_regen:                 {name:<%= channels['poc.go_kwh_regen'].channelId %>,              values:[]},
        go_inflow_rate:               {name:<%= channels['poc.go_inflow_rate'].channelId %>,            values:[]}
    };

    var formatDate = function(str){
        var c1 = new Date(str);
        var c2 = (c1.getTime() / 1000);
        c2 = Math.floor(c2);
        return c2.toString();
    };

    var updateTable = function(chID, chName){
        
        var start = $('#datepicker').find('#fromDate');
        //console.log({start:start.val()});
        dateString = start.val().replace(/-/g, "/");
        start = formatDate(dateString);
        
        var end = $('#datepicker').find('#toDate');
        //console.log({end:end.val()});
        dateString = end.val().replace(/-/g, "/");
        end = formatDate(dateString);
        
        var apiData = "&nodelist[0][nodeId]=" + nodeID.toString() + "&nodelist[0][channelId]=" + chID.toString();
        apiData += "&start=" + start + "&end=" + end;
        
        $.ajax({
            url: '<%= rootURL %>' + '/api2/Nodechannels',
            data: apiData,
            dataType: "json",
            type: "GET",
            success: function(data) {
                var dataPoints = data.listofstreams[0];
                for(var i = dataPoints.stream.length-1; i > 0; i--){
                    var dpt = dataPoints.stream[i];
                    var timestamp = dpt.x;
                    var val = dpt.y;
                    channelData[chName]['values'].push({t:timestamp, val:val});
                    if (!tableData.hasOwnProperty(timestamp)){
                        tableData[timestamp] = {};
                    }
                    tableData[timestamp][chName] = val;
                }
            }
        });
    };
$(document).ready(function(){
    var $output = $('#output');
    for (var channel in channelData){
        if(channelData.hasOwnProperty(channel)){
            updateTable(channelData[channel]['name'], channel);
        }
    }
    
    var buildTable = function(){
        for (var timestp in tableData){
            if(tableData.hasOwnProperty(timestp)){
                var date = new Date(parseInt(timestp) * 1000);
                var dateString = (date.getMonth() +1) + "/" + date.getDate() + "/" + date.getFullYear();
                
                var row = "<tr><td>" + dateString + "</td>";
                row += "<td>" + tableData[timestp]['go_percent_run']+ "</td>";
                row += "<td>" + tableData[timestp]['go_kwh'] + "</td>";
                row += "<td>" + tableData[timestp]['go_electricity_cost'] + "</td>";
                row += "<td>" + tableData[timestp]['go_peak_load'] + "</td>";
                row += "<td>" + tableData[timestp]['go_min_load'] + "</td>";
                row += "<td>" + tableData[timestp]['go_average_spm'] + "</td>";
                row += "<td>" + tableData[timestp]['go_production_calculated'] + "</td>";
                row += "<td>" + tableData[timestp]['go_polished_rod_hp'] + "</td>";
                row += "<td>" + tableData[timestp]['go_lifting_cost'] + "</td>";
                row += "<td>" + tableData[timestp]['go_fluid_above_pump'] + "</td>";
                row += "<td>" + tableData[timestp]['go_pump_intake_pressure'] + "</td>";
                row += "<td>" + tableData[timestp]['go_kwh_regen'] + "</td>";
                row += "<td>" + tableData[timestp]['go_inflow_rate'] + "</td></tr>";
                console.log(row);
                $output.append(row);
                 
            }
        }
    };
    
    //console.log({tableData:tableData, channelData:channelData});
    setTimeout(buildTable, 3000);
    
    
    
    
});

</script>
