
$(function() {
  $('button.reload-page').click(function() {
    window.location.reload();
  });

  if(window.remoteDevice && typeof window.remoteDevice.infoHistory != 'undefined' && window.remoteDevice.infoHistory.length) {
    // Create a panel with a canvas inside
    var canvas = $('<canvas>').appendTo(
      $('<div>')
      .addClass('panel-body')
      .appendTo(
        $('<div>')
        .addClass('panel panel-primary')
        .append(
          $('<div>')
          .addClass('panel-heading')
          .append(
            $('<h3>')
            .addClass('panel-title')
            .text(' Battery graph')
            .prepend(
              $('<span>')
              .addClass('glyphicon glyphicon-stats')
            )
          )
        )
        .insertAfter( $('.device-info-panel') )
      )
    );

    // Graph options
    var maxTime, annotations = [], unitStepSize;

    // If we know when the simulation was started, add an annotation
    if(window.remoteDevice.firstSimInfo) {
      annotations.push({
        type: 'line',
        mode: 'vertical',
        scaleID: 'x-axis-0',
        value: window.remoteDevice.firstSimInfo.date,
        borderColor: 'blue',
        borderWidth: 1
      });
    }

    // If we have an estimated end, show it in the graph as an annotation
    if(window.remoteDevice.ebt && window.remoteDevice.ebt.end) {
      annotations.push({
        type: 'line',
        mode: 'vertical',
        scaleID: 'x-axis-0',
        value: window.remoteDevice.ebt.end,
        borderColor: 'red',
        borderWidth: 1
      });

      maxTime = new Date(window.remoteDevice.ebt.end);
    } else {
      maxTime = new Date(window.remoteDevice.infoHistory[window.remoteDevice.infoHistory.length - 1 ].date);
    }

    // Round up to the next full minute to prevent labels, values and annotations from being cut
    // off at the end of the scale.
    maxTime = new Date(+maxTime + 60 * 1000);
    maxTime.setSeconds(0);

    // To prevent overlapping text at the right end of the scale, we need to ensure that the
    // difference between start and end (in minutes) is a multiple of the unit step size. This
    // means that only the very first and last label will be shown if the difference is not a
    // multiple of a positive integer less than 10.
    var totalTimeCovered = Math.round((+maxTime - +new Date(window.remoteDevice.infoHistory[0].date)) / 60000);
    var suggestedIntervalCounts = [ 5, 6, 7, 8, 9, 4, 3, 2, 1 ];
    for(var i = 0; i < suggestedIntervalCounts.length; i++) {
      unitStepSize = Math.round(totalTimeCovered / suggestedIntervalCounts[i]);
      if(totalTimeCovered % unitStepSize == 0) {
        break;
      }
    }

    // Finally, create the chart
    var chart = new Chart(canvas, {
      type: 'line',
      data: {
        datasets: [{
          label: 'Battery level (%)',
          backgroundColor: 'rgba(60, 220, 60, 0.2)',
          borderColor: 'rgba(30, 240, 30, 0.4)',
          data: window.remoteDevice.infoHistory.map(function(entry) {
            return {
              x: entry.date,
              y: Math.floor(entry.info.battery.level * 100)
            };
          }).filter(function(entry, index, entries) {
            return (index == 0 ||                     // first entry
                    index == entries.length - 1 ||    // last entry
                    entries[index - 1].y != entry.y); // value changed
          })
        }]
      },
      options: {
        annotation: {
          annotations: annotations
        },
        animation: false,
        scales: {
          yAxes: [{
            type: 'linear',
            ticks: {
              max: 100,
              min: 0,
              stepSize: 10
              }
          }],
          xAxes: [{
            type: 'time',
            time: {
              unit: 'minute',
              unitStepSize: unitStepSize,
              displayFormats: {
                minute: 'HH:mm'
              },
              max: maxTime
            }
          }]
        }
      }
    });
  }
});
