<table class="table-report" style="width:100%">
  <tr>
    <th>Grupo</th>
    <td colspan="2"><%= @vehicle.group.name %></td>
  </tr>
  <tr>
    <th>Vehículo</th>
    <td colspan="2"><%= @vehicle.name %></td>
  </tr>
  <% if !params[:only_graph] %>
    <tr>
      <th>Fecha</th>
      <th>Temperatura</th>
      <th>Ubicación</th>
    </tr>
    <tr>
      <% @positions.order(fixtime: :asc).each do |position| %>
        <% attributes = JSON.parse(position.attributes["attributes"]) %>
        <% if attributes["temp1"].present? %>
        <tr>
          <td class="data-row"><%= position.fixtime.strftime("%F %T") %></td>
          <% color_class = attributes['temp1'] || '0' %>
          <% color_class = color_class.to_f > 0 ? "red-bg" : "green-bg" %>
          <td class="data-row <%= color_class %>"><%= attributes["temp1"].present? ? attributes["temp1"] : 'n/a' %></td>
          <td class="data-row"><a href="<%= position.gm_link %>">Ver ubicación</a></td>
        </tr>
      <% end %>
    <% end %>
    </tr>
  <% end %>
</table>
<br><br>
<% if params[:only_graph].present? %>
  <div style="width:1300px;height: 400px; text-align: center">
    <canvas id="myChart" style="width:100%;height: 100%;"></canvas>
  </div>
<% end %>
<script>

  'use strict';
  (function(setLineDash) {
    CanvasRenderingContext2D.prototype.setLineDash = function() {
      if(!arguments[0].length){
        arguments[0] = [1,0];
      }
      // Now, call the original method
      return setLineDash.apply(this, arguments);
    };
  })(CanvasRenderingContext2D.prototype.setLineDash);
  Function.prototype.bind = Function.prototype.bind || function (thisp) {
    var fn = this;
    return function () {
      return fn.apply(thisp, arguments);
    };
  };

  var ctx = document.getElementById("myChart").getContext('2d');

  function showTooltip(tooltipModel, title, index, count_show_tooltip){
    //if(index % 20 != 0) return;
    tooltipModel.title = [title];
    tooltipModel.body = [];
    tooltipModel.opacity = 1;
    tooltipModel.yAlign = "center";
    tooltipModel.caretX = tooltipModel._model.x;
    tooltipModel.caretY = tooltipModel._model.y;
    tooltipModel._bodyAlign = "left";
    tooltipModel._bodyFontFamily = "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif";
    tooltipModel._bodyFontStyle = "normal";
    tooltipModel._footerAlign = "left";
    tooltipModel._footerFontFamily = "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif";
    tooltipModel._footerFontStyle = "bold";
    tooltipModel._titleAlign = "left";
    tooltipModel._titleFontFamily = "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif";
    tooltipModel._titleFontStyle = "bold";
    tooltipModel.yPadding = 6;
    tooltipModel.xPadding = 6;
    if(!tooltipModel.title) return;
    // Tooltip Element
    var tooltipEl = document.getElementById('chartjs-tooltip' + index);

    // Create element on first render
    if (!tooltipEl) {
      tooltipEl = document.createElement('div');
      tooltipEl.id = 'chartjs-tooltip' + index;
      tooltipEl.innerHTML = "<table></table>";
      document.body.appendChild(tooltipEl);
    }

    // Hide if no tooltip
    if (tooltipModel.opacity === 0) {
      tooltipEl.style.opacity = 0;
      return;
    }
    // Set caret Position
    tooltipEl.classList.remove('above', 'below', 'no-transform');
    if (tooltipModel.yAlign) {
      tooltipEl.classList.add(tooltipModel.yAlign);
    } else {
      tooltipEl.classList.add('no-transform');
    }

    function getBody(bodyItem) {
      return bodyItem.lines;
    }

    if (tooltipModel.body) {
      var titleLines = tooltipModel.title || [];
      var bodyLines = tooltipModel.body.map(getBody);

      var innerHtml = '<thead>';

      titleLines.forEach(function(title) {
        innerHtml += '<tr><th>' + title + '</th></tr>';
      });
      innerHtml += '</thead><tbody>';
      innerHtml += '</tbody>';

      var tableRoot = tooltipEl.querySelector('table');
      tableRoot.innerHTML = innerHtml;
    }
    // `this` will be the overall tooltip
    var position = myChart.canvas.getBoundingClientRect();
    // Display, position, and set styles for font

    tooltipEl.style.opacity = 1;
    tooltipEl.style.position = 'absolute';

    var posTop = position.top + window.pageYOffset + tooltipModel.caretY;
    var posLeft = position.left + window.pageXOffset + tooltipModel.caretX - 20;
    ctx.beginPath();
    ctx.moveTo(tooltipModel.caretX, tooltipModel.caretY);
    if(<%= @invert_labels_position %>) {
      var invertLabels = count_show_tooltip % 2 == 0;
    } else {
      var invertLabels = count_show_tooltip % 2 != 0;
    }
    if(invertLabels){
      if(<%= params[:show_html].present? %>){
        posTop -= 30;
      } else {
        posTop -= 100;
      }
      ctx.lineTo(tooltipModel.caretX, tooltipModel.caretY - 10);
    } else {
      if(<%= params[:show_html].present? %>){
        posTop += 5;
      } else {
        posTop -= 60;
      }
      ctx.lineTo(tooltipModel.caretX, tooltipModel.caretY + 10);
    }

    ctx.lineWidth = 2;
    ctx.strokeStyle = 'rgba(46,147,217,0.7)';
    ctx.stroke();
    tooltipEl.style.top = posTop  + 'px';
    tooltipEl.style.left = posLeft + 'px';
    tooltipEl.style.fontFamily = tooltipModel._bodyFontFamily;
    tooltipEl.style.fontSize = '10px';
    tooltipEl.style.fontStyle = tooltipModel._bodyFontStyle;
    tooltipEl.style.padding = tooltipModel.yPadding + 'px ' + tooltipModel.xPadding + 'px';
    tooltipEl.style.pointerEvents = 'none';
  }

  Chart.plugins.register({
    beforeRender: function (chart) {
      if (chart.config.options.showAllTooltips) {
        // create an array of tooltips
        // we can't use the chart tooltip because there is only one tooltip per chart
        chart.pluginTooltips = [];
        chart.config.data.datasets.forEach(function (dataset, i) {
          chart.getDatasetMeta(i).data.forEach(function (sector, j) {
            chart.pluginTooltips.push(new Chart.Tooltip({
              _chart: chart.chart,
              _chartInstance: chart,
              _data: chart.data,
              _options: chart.options.tooltips,
              _active: [sector]
            }, chart));
          });
        });

        // turn off normal tooltips
        chart.options.tooltips.enabled = false;
      }
    },
    afterDraw: function (chart, easing) {
      if (chart.config.options.showAllTooltips) {
        // we don't want the permanent tooltips to animate, so don't do anything till the animation runs atleast once
        if (!chart.allTooltipsOnce) {
          if (easing !== 1)
            return;
          chart.allTooltipsOnce = true;
        }
        // turn on tooltips
        chart.options.tooltips.enabled = true;
        var count = chart.pluginTooltips.length;
        var total_tooltips = parseInt(count / 50);
        var count_show_tooltip = 0;
        Chart.helpers.each(chart.pluginTooltips, function (tooltip) {
          var tooltipModel = tooltip._active[0]
          var index = tooltipModel._index;
          var title = tooltipModel._chart.config.data.datasets[0].data[index].toFixed(1);
          if(index % total_tooltips == 0){
            showTooltip(tooltipModel, title, index, count_show_tooltip);
            count_show_tooltip++;
          }
        });
        chart.options.tooltips.enabled = false;
      }
    }
  });

  var myChart = new Chart(ctx, {
    type: 'line',
    responsive: true,
    data: {
      labels: <%= @dates.to_json.html_safe %>,
      datasets: [{
        label: 'Temperatura', // Name the series
        data: <%= @values.to_json.html_safe %>, // Specify the data values array
        fill: false,
        borderColor: '#000000', // Add custom color border (Line)
        backgroundColor: '#2196f3', // Add custom color background (Points and Fill)
        borderWidth: 1, // Specify bar border width
        javascript_delay: 5000
      }]},
    options: {
      showAllTooltips: true,
      scales: {
        yAxes: [{
          scaleLabel: {
            display: true,
            labelString: 'Temperatura (°C)'
          }
        }],
        xAxes: [{
          scaleLabel: {
            display: true,
            labelString: 'Fechas'
          }
        }]
      },
      elements: {
        point:{
          pointStyle: 'cicle',
          radius: 0
        }
      },
      tooltips: {
        enabled: true,
        mode: 'x',
        position: 'average',
        titleFontSize: 6,
        titleFontColor: 'rgba(0,0,0,0)',
        backgroundColor: 'rgba(0,0,0,0)',
        callbacks: {
          title: function (tooltipItem, data) {
            return tooltipItem[0].index + "@" + tooltipItem[0].yLabel;
          },
          label: function(tooltipItems, data) {
            return "";
          },
          footer: function (tooltipItem, data) { return ""; }
        },
        custom: function(tooltipModel) {
        //   showTooltip(tooltipModel);
        }
      }
    }
  });

</script>