/* EPS@ISEP Team 1
 *Project: Floating Trash Collector
 *This is the code that processes and displays the pertentage gauge meter
 *This is JavaScript code
*/
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'></script>
<script type='text/javascript' src='https://www.google.com/jsapi'></script>
<script type='text/javascript'>

  // set your channel id here
  var channel_id = 1067178;
  // set your channel's read api key here if necessary
  var api_key = '75RMBP10FJKZP6L0';
  // maximum value for the gauge
  var max_gauge_value = 100;
  // global variables
  var chart, charts, data;

  // load the google gauge visualization
  google.load('visualization', '1', {packages:['gauge']});
  google.setOnLoadCallback(initChart);

  // display the data
  function displayData(gauge_name,point) {
    data.setValue(0, 0, gauge_name);
    data.setValue(0, 1, point);
    chart.draw(data, options);
  }

  // load the data
  function loadData() {
    // variables
    var distance;
    var percent;
    var gauge_name;
    var max = 50;
    var min = 25;
    
    // get the data from thingspeak
    $.getJSON('https://api.thingspeak.com/channels/' + channel_id + '/feed/last.json?api_key=' + api_key, function(data) {

      // get the data point
      distance = data.field1;

      // if the is a data point, present it
      if(distance){
       if(distance != 0) // if there is no problem with the SONAR, proceed
       {
        if(distance <= max && distance >= min) // readings within the normal operating range
         {
          percent = ((distance - max)/(min - max)) * 100; // converts the reading into a percentual value
          displayData('Capacity',percent);  // displays the percentage in the gauge meter       
           if(percent >= 83) // entering red zone on the gauge
            displayData('Full!',percent); // 
        }else displayData('Inconclusive!',0);
       }else displayData('Sensor Lost!',0);
      }else displayData('No data!',0);
    });
  }

  // initialize the chart
  function initChart() {

    data = new google.visualization.DataTable();
    data.addColumn('string', 'Label');
    data.addColumn('number', 'Value');
    data.addRows(1);

    chart = new google.visualization.Gauge(document.getElementById('gauge_div'));
    options = {width: 200, height: 200, redFrom: 80, redTo: 100, minorTicks: 5};

    loadData();

    // load new data every 15 seconds
    setInterval('loadData()', 15000);
  }

</script>

