import LineHeatmap from "./lineHeatmap";
import "nouislider";

const template = `<div>
  <div class="line-heatmap-controls">
    <div id="line-heatmap-slider"></div>
  </div>
  <div id="line-heatmap-canvas">
  </div>
</div>
`;

const stateObject = {};

function init (elementId, logString) {
  const el = document.getElementById(elementId);
  el.innerHTML = template;
  const logData = logTransform(logString);
  // create container
  const heatmap = new LineHeatmap('line-heatmap-canvas');
  heatmap.create();
  heatmap.setTrackData(logData);

  const html5Slider = document.getElementById('line-heatmap-slider');
  noUiSlider.create(html5Slider, {
      start: [1, logData.length],
      connect: true,
      margin: 1,
      range: {
          'min': 1,
          'max': logData.length
      }
  });
  
  stateObject['container'] = el;
  stateObject['heatmap'] = heatmap;
  stateObject['data'] = logData;
  stateObject['slider'] = html5Slider;

  html5Slider.noUiSlider.on('update', function (values, handle) {
    const logValues = this.get();
    console.log(logValues);
    const newData = stateObject['data'].slice(+logValues[0]-1, +logValues[1] + 1);
    console.log(newData);
    stateObject['heatmap'].setTrackData(newData);
  });
}

function updateLogString (logString) {
  const logData = logTransform(logString);
  stateObject['data'] = logData;
  stateObject['slider'].noUiSlider.updateOptions({
    range: {
        'min': 1,
        'max': logData.length
    }
  });
  stateObject['heatmap'].setTrackData(logData); 
}

function logTransform (logString) {
  const data = logString.split("\n")
  .filter(v => v.split(',').length > 3)
  .map(v => {
    const o = JSON.parse('[' + v + ']');
    return {
      x: o[0],
      y: o[1],
      value: 1
    };
  });
  return data;
}

export default {
  init,
  updateLogString
}