import Component from 'ember-component';
import computed from 'ember-computed';
import DetailsReport, {
  FILTER_OPTIONS_CUTOFF,
  METRIC_I18N
} from 'web-client/utilities/video-stats/details-report';
import formatNumber from 'web-client/utilities/format-number';

const VIDEO_DETAILS_GRAPH_OPTIONS = {
  fill: false,
  lineTension: 0,
  tooltips: {
    mode: 'label',
    enabled: true,
    backgroundColor: 'rgba(0,0,0,0.8)',
    titleFontFamily: `'Helvetica Neue', 'Helvetica', 'Arial', sans-serif`,
    titleFontSize: 12,
    titleFontColor: '#fff',
    titleSpacing: 5,
    titleMarginBottom: 6,
    bodyFontColor: '#fff',
    bodyFontStyle: 'normal',
    bodySpacing: 5,
    xPadding: 6,
    yPadding: 6,
    caretSize: 4,
    multiKeyBackground: 'rgba(0,0,0,0)',
    callbacks: {
      label(item, data) {
        let dataset = data.datasets[item.datasetIndex];
        let value = formatPointValue(item.yLabel, dataset.metric);
        return ` ${dataset.label}: ${value}`;
      },
      labelColor(item, chartInstace) {
        let bgColor = `${chartInstace.config.data.datasets[item.datasetIndex].backgroundColor}`;
        return {
          borderColor: bgColor,
          backgroundColor: bgColor
        };
      }
    }
  },
  legend: {
    position: 'bottom',
    labels: {
      boxWidth: 12
    }
  },
  responsive: true,
  maintainAspectRatio: false,
  scales: {
    xAxes: [
      {
        gridLines: {
          display: false,
          color: 'rgba(0,0,0,0.05)',
          zeroLineColor: 'rgba(0,0,0,0.05)'
        },
        ticks: {
          min: 0,
          suggestedMax: 1,
          maxTicksLimit: 7
        }
      }
    ],
    yAxes: [
      {
        gridLines: {
          display: true
        },
        ticks: {
          min: 0,
          suggestedMax: 1,
          maxTicksLimit: 6
        }
      }
    ]
  }
};

const GRAPH_COLORS = [
  '#6441A4',
  '#9A7FCC',
  '#5177FF',
  '#51CAFF',
  '#3CC6AE'
];

function formatPointValue(value, metric) {
  let options = { separator: ',' };

  if (metric === 'averageviewduration') {
    options.scale = 2;
  }

  return formatNumber(value, options);
}

export default Component.extend({
  init() {
    this._super(...arguments);

    this.videoDetailsGraphOptions = VIDEO_DETAILS_GRAPH_OPTIONS;

    if (!this.today) {
      this.set('today', new Date());
    }

    if (this.video) {
      this.minimumDate = this.video.created_at;
    }
  },

  report: computed('data', 'today', function() {
    let newReport = DetailsReport.create({
        data: this.get('data.analytics'),
        today: this.get('today')
    });

    return newReport;
  }),

  formattedChartData: computed('report.chartDataSets', function() {
    let chartDataSets = this.get('report').get('chartDataSets');

    return this.formatLineChartData(chartDataSets);
  }),

  actions: {
    setStartDate(date) {
      this.get('report').set('startDate', date);
    },
    setEndDate(date) {
      this.get('report').set('endDate', date);
    },
    setMetric(metric) {
      this.get('report').set('selectedMetric', metric);
    },
    setFilter(filter) {
      this.get('report').set('selectedFilter', filter);
    }
  },

  /**
   * Turns: { 'viewcount': [points], 'minuteswatched': [points] }
   * into Chart.js data format.
   */
  formatLineChartData(dataSets) {
    let lineChartData = { labels: [], datasets: [] };
    if (!dataSets || Object.keys(dataSets).length === 0) {
      return lineChartData;
    }

    let dataSetLabels = Object.keys(dataSets);
    dataSets[dataSetLabels[0]].forEach(point => {
      lineChartData.labels.push(point.x);
    });

    for(let lineIndex = 0; lineIndex < FILTER_OPTIONS_CUTOFF && lineIndex < dataSetLabels.length; lineIndex++) {
      let label = dataSetLabels[lineIndex];
      let dataSet = dataSets[label];
      let lineData = this.formatLineData(label, lineIndex, dataSet);

      lineChartData.datasets.push(lineData);
    }

    return lineChartData;
  },

  formatLineData(label, lineIndex, dataSet) {
    let graphColor = GRAPH_COLORS[lineIndex % GRAPH_COLORS.length];
    let borderColor = "#fff";

    return {
      label: METRIC_I18N[label] || label,
      metric: label,
      data: dataSet,
      fill: false,
      lineTension: 0,
      borderWidth: 2,
      borderColor: graphColor,
      backgroundColor: graphColor,
      pointRadius: 5,
      pointBorderColor: borderColor,
      pointBackgroundColor: graphColor,
      pointBorderWidth: 2,
      pointHoverRadius: 10,
      pointHoverBorderWidth: 4,
      pointHoverBorderColor: borderColor
    };
  }
});
