'use strict';

var KnokLinearPlugin = (function () {
  var getCanvasLinearGradient = function (ctx, colors, options) {
    var y0 = options.y0 || 0;
    var y1 = options.y1 || 100;
    var gradient = ctx.createLinearGradient(0, y0, 0, y1);
    colors.forEach(function (value) {
      var index = value[0];
      var color = value[1];
      gradient.addColorStop(index, color);
    });
    return gradient;
  };

  return {
    id: 'knok-linear',
    afterDatasetDraw: function (chart, datasets, options) {
      // console.error([chart, datasets, options]);

      var options = chart.options || {};
      var plugins = options.hasOwnProperty('plugins') ? options.plugins : [];
      if (Array.isArray(plugins)) {
        var is = plugins.indexOf(this.id) != -1 || plugins.indexOf(KnokLinearPlugin) != -1;
      } else {
        var is = plugins.hasOwnProperty(this.id) && plugins[this.id] != false;
      }

      if (!is) {
        return;
      }

      var context = chart.ctx;
      var chartArea = chart.chartArea;
      var meta = datasets.meta;

      var lastElement = null;
      // var tooltipEl = null;

      meta.data.forEach(function (element, index) {
        if (!element._model.skip) {
          lastElement = element;
        }
      });

      var drawCustomCurrentRate = options.hasOwnProperty('drawCustomCurrentRate') ? options.drawCustomCurrentRate : true;
      var currentRateColor = options.hasOwnProperty('currentRateColor') ? options.currentRateColor : 'rgba(0, 186, 255, 1)';
      var endedStatus = options.hasOwnProperty('endedStatus') ? options.endedStatus : null;
      var listItemMode = options.hasOwnProperty('listItemMode') ? options.listItemMode : false;
      if (lastElement) {
        context.save();
        if(!listItemMode) {
          if (!endedStatus) {
            context.beginPath();          
            context.moveTo(lastElement._model.x, lastElement._model.y + 20);
            context.lineTo(lastElement._model.x, lastElement._model.y - 20);
            context.strokeStyle = currentRateColor;
            context.lineWidth = 1;
            context.stroke();
            // var center = lastElement._model.y / chartArea.bottom; 
            // var gradient = getCanvasLinearGradient(context, [
            //   [0, 'rgba(255, 255, 255, 0.15)'],
            //   [(center < 1 ? center : 1), 'rgba(0, 186, 255, 0.15)'],
            //   [1, 'rgba(255, 255, 255, 0.15)']
            // ], {
            //   y0: chartArea.top,
            //   y1: chartArea.bottom
            // });
            // context.fillStyle = gradient;
            // context.fillRect(lastElement._model.x - 12, chartArea.top, 24, chartArea.bottom);          
            context.closePath();
          }
        } else {
          // var center = lastElement._model.y / chartArea.bottom; 
            var gradient = getCanvasLinearGradient(context, [
              [0, 'rgba(255, 255, 255, 0.15)'], 
              [1, currentRateColor]
            ], {
              y0: 0,
              y1: 100
            });
            context.beginPath();
            context.fillStyle = gradient;
            context.arc(lastElement._model.x, lastElement._model.y, 12, 0, 2 * Math.PI, false);
            context.fill();
            context.closePath();
            context.save();
            context.restore();
        }

        //Draw rate mark
        if(drawCustomCurrentRate){

        }
        context.restore();
      }
    },
    afterEvent: function (chart, event, options) {

      function hitTheTarget(x, y, val) {
        const dist = 12;
        return  (x <= val.x + dist && x >= val.x-dist/2 && y <= val.y+dist && y >= val.y-dist/2);
      }

      if (event.type === 'mousemove' && chart.hasOwnProperty('pricesTicks') && chart.pricesTicks && chart.pricesTicks.length > 0) {
        var tooltipIsShown = false;
        chart.pricesTicks.forEach(function(tick, t) {
        if (!tooltipIsShown && hitTheTarget(event.x, event.y, tick)) {
          var tooltipEl = document.getElementById('chartjs-tooltip-2');

          if (!tooltipEl) {
              tooltipEl = document.createElement('div');
              tooltipEl.id = 'chartjs-tooltip-2';
              tooltipEl.innerHTML = "<div></div>";
              document.body.appendChild(tooltipEl);
          }
          var divRoot = tooltipEl.querySelector('div');
          divRoot.innerHTML = `<bs-tooltip-container role="tooltip" class="tooltip in tooltip-top bs-tooltip-top top knk-tooltip show">
            <div class="tooltip-arrow arrow"></div>
            <div class="tooltip-inner">${tick.label}</div></bs-tooltip-container>`;

          // `this` will be the overall tooltip
          var position = chart.canvas.getBoundingClientRect();

          // Display, position, and set styles for font
          tooltipEl.style.opacity = 1;
          tooltipEl.style.position = 'absolute';
          tooltipEl.style.zIndex = 1001;
          tooltipEl.style.left = position.left + tick.x - 42 +  'px';
          tooltipEl.style.top = position.top + tick.y - 54 - document.documentElement.offsetTop + 'px';
          tooltipIsShown = true;
          return;
        }
      });
      if (!tooltipIsShown) {
        var tooltipEl = document.getElementById('chartjs-tooltip-2');
        if (tooltipEl) {
          tooltipEl.style.opacity = 0;
          return;
        }
      }
      }
    }
  };
})();

var exports = module.exports = {};
exports.KnokLinearPlugin = KnokLinearPlugin;
