<?php

    require_once './config/database.php';
    
//    $power_db = mysql_query("SELECT `U`, `I`, `P`, `Q`, `S`, `n`, `time`, `date` FROM `power`");
    $power_db = mysql_query("SELECT `U`, `I`,`time` FROM `power` ORDER BY `date` DESC, `time` DESC LIMIT 100");
    
   // echo "<b>Measured value: </b><br><br>";
//    
//    while ($power = mysql_fetch_array($power_db)) 
//    {
//        $U_db = $power['U'];
//        $I_db = $power['I'];
//        $P_db = $power['P'];
//        $Q_db = $power['Q'];
//        $S_db = $power['S'];
//        $n_db = $power['n'];
//        $time_db = $power['time'];
//        $date_db = $power['date'];
//        
//        echo 'U = '.$U_db.', I = '.$I_db.', P = '.$P_db.', Q = '.$Q_db.', S = '.$S_db.', ny = '.$n_db.' at '.$time_db.'h '.$date_db.'<br>';
//    }
    
    
    $rows = array();
    //flag is not needed
    $flag = true;
    $table = array();
    $table['cols'] = array(

        // Labels for your chart, these represent the column titles
        // Note that one column is in "string" format and another one is in "number" format as pie chart only required "numbers" for calculating percentage and string will be used for column title
        array('label' => 'U', 'type' => 'string'),
        array('label' => 'time', 'type' => 'number')

    );

    $rows = array();
    while($r = mysql_fetch_assoc($power_db)) {
        $temp = array();
        // the following line will be used to slice the Pie chart
        $temp[] = array('v' => (int) $r['time']); 
        // Values of each slice
        $temp[] = array('v' => (string) $r['U']); 
        $rows[] = array('c' => $temp);
    }

    $table['rows'] = array_reverse($rows);
    $jsonTable = json_encode($table);
    
    
?>


  <html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
      
    var chart = null;
    var options = null;
    var gaugeUData = null;
    var gaugeIData = null;
    var gaugePData = null;
    var gaugeUOptions = null;
    var gaugeIOptions = null;
    var gaugePOptions = null;
    var gaugeU = null;
    var gaugeI = null;
    var gaugeP = null;
      
    google.charts.load('current', {'packages':['gauge','corechart']});
    google.charts.setOnLoadCallback(drawGaugeVoltage);
    google.charts.setOnLoadCallback(drawGaugeCurrent);
    google.charts.setOnLoadCallback(drawGaugePower);
    
    google.charts.setOnLoadCallback(drawChart);
      
      
      function loadData()
      {
          $.ajax({
              url: './loadData.php',
              success: function(returnVal){
                  var data = new google.visualization.DataTable(returnVal);
                  chart.draw(data, options);
                 // gauge.draw(data, gaugeOptions);
              }
          });
          
         $.ajax({
              url: './loadDataGauge.php',
              success: function(returnVal){
                  returnVal = JSON.parse(returnVal);
                  //var data = new google.visualization.DataTable(returnVal);
                 // gaugeUData.setValue(0, 1, returnVal['U']/100);
                  gaugeUData.setCell(0, 0, returnVal['U']/100);
                  gaugeIData.setCell(0, 0, returnVal['I']/1000);
                  gaugePData.setCell(0, 0, returnVal['P']/10);
                  gaugeU.draw(gaugeUData, gaugeUOptions);
                  gaugeI.draw(gaugeIData, gaugeIOptions);
                  gaugeP.draw(gaugePData, gaugePOptions);
                  if (returnVal['R'] == 2)
                  {
                      $('.gauge').fadeTo(0, .25);
                      $('#error').css('visibility', 'visible');
                  }
                  else
                  {
                      $('.gauge').fadeTo(0, 1);
                      $('#error').css('visibility', 'hidden');
                  }
                  
                  $('.status_info').hide();
                  $('#status_'+returnVal['R']).show();
                  
              },
              error: function (jqXHR, textStatus, errorThrown) {
                        console.log(jqXHR);
                    }
          });
      }
        
      function drawChart() {
        var data = new google.visualization.DataTable(<?=$jsonTable?>);

        options = {
          title: 'Výkon',
          curveType: 'none',
          legend: { position: 'none' }
        };

        chart = new google.visualization.LineChart(document.getElementById('curve_chart'));

        chart.draw(data, options);
      }
      
     /* function drawGaugeVoltage() {
        gaugeUData = google.visualization.arrayToDataTable([
          ['Label', 'Value'],
          ['Napětí', 230]
        ]);

        gaugeUOptions={min: 180, max: 280, greenFrom: 207, greenTo: 253 ,yellowFrom: 180, yellowTo: 207, redFrom: 253, redTo: 280, minorTicks: 1};


        gaugeU = new google.visualization.Gauge(document.getElementById('gauge_div_voltage'));
        gaugeU.draw(gaugeUData, gaugeUOptions);
      }*/
      
      function drawGaugeVoltage() {
        gaugeUData = new google.visualization.DataTable();
        gaugeUData.addColumn('number', 'Napětí');
        gaugeUData.addRows(2);
        gaugeUData.setCell(0, 0, 241);

        gaugeUOptions={min: 180, max: 280, greenFrom: 207, greenTo: 253 ,yellowFrom: 180, yellowTo: 207, redFrom: 253, redTo: 280, minorTicks: 1};


        gaugeU = new google.visualization.Gauge(document.getElementById('gauge_div_voltage'));
        gaugeU.draw(gaugeUData, gaugeUOptions);
      }
    
    function drawGaugeCurrent() {
      gaugeIData = new google.visualization.DataTable();
      gaugeIData.addColumn('number', 'Proud');
      gaugeIData.addRows(2);
      gaugeIData.setCell(0, 0, 12);

      gaugeIOptions={min: 0, max: 20, greenFrom: 0, greenTo: 14 , yellowFrom: 14, yellowTo: 16, redFrom: 16, redTo: 20, minorTicks: 1};


      gaugeI = new google.visualization.Gauge(document.getElementById('gauge_div_current'));
      gaugeI.draw(gaugeIData, gaugeIOptions);
    }
    
    function drawGaugePower() {
      gaugePData = new google.visualization.DataTable();
      gaugePData.addColumn('number', 'Výkon');
      gaugePData.addRows(2);
      gaugePData.setCell(0, 0, 250);

      gaugePOptions={min: 0, max: 4800, greenFrom: 0, greenTo: 3000 , yellowFrom: 3000, yellowTo: 3600, redFrom: 3600, redTo: 4800, minorTicks: 1};


      gaugeP = new google.visualization.Gauge(document.getElementById('gauge_div_power'));
      gaugeP.draw(gaugePData, gaugePOptions);
    }
    
    function changeTemp(dir) {
      $.ajax({
          url: './toggle.php',
          dataType: 'text',
          data: {'status': dir},
          method: "POST",
          success: function(retVal)
          {
              console.log(retVal);
          }
      });
    }
    
      window.setInterval(loadData, 500);
    </script>
  </head>
  
  <style>
.button {
    background-color: #4CAF50;  /* Green */
    border: none;
    color: white;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    margin: 4px 2px;
    cursor: pointer;
    padding-left: 0;
    padding-right: 0;
    width: 100%;
}
.button2 {background-color: #f44336;} /* Red */ 

</style>

  <body>
    <div id="curve_chart" style="width: 95%; height: 500px"></div>
    <h2 id="error" style="visibility: hidden; margin-left: 7vw;">Ztráta spojení - hodnoty nejsou platné!</h2>
    <div class="gauge" id="gauge_div_voltage" style="width:12.5vw; height: 12.5vw; float: left; margin-left: 7vw; "></div>
    <div class="gauge" id="gauge_div_current" style="width:12.5vw; height: 12.5vw; float: left; margin-left: 3vw;"></div>
    <div class="gauge" id="gauge_div_power"   style="width:12.5vw; height: 12.5vw; float: left; margin-left: 3vw;"></div>
    <div style="width: 12.5vw; float: left; margin-left: 3vw;">
        <h2 class="status_info" id="status_2" style="text-align: center; padding: .75vw; background: #FFFFDD; display: none;">Nepřipojeno</h2>
        <h2 class="status_info" id="status_1" style="text-align: center; padding: .75vw; background: #CCFFDD; display: none;">Zapnuto</h2>
        <h2 class="status_info" id="status_0" style="text-align: center; padding: .75vw; background: #FFDDDD; display: none;">Vypnuto</h2>
        
        <input type="button" class="button" value="Zapnout" onclick="changeTemp(1)" />
        <br/>
        <input type="button" class="button button2" value="Vypnout" onclick="changeTemp(0)" />
    </div>
  </body>
</html>