/* globals i18n */
import { AGGREGATION_HOURLY, AGGREGATION_DAILY } from 'web-client/models/video-stats/channel-timeseries';
import moment from 'moment';
import computed from 'ember-computed';
import { TimeSeries, parseTimeSeriesData } from 'web-client/utilities/video-stats/time-series';
import EmberObject from 'ember-object';

export const DEFAULT_METRIC = 'viewcount';
export const HOURLY_AGGREGATION_CUTOFF = 48;
export const FILTER_OPTIONS_CUTOFF = 5;

export const METRIC_I18N = {
  'viewcount': i18n('View Count'),
  'averageviewduration': i18n('Average View Duration'),
  'minuteswatched': i18n('Minutes Watched')
};

export const FILTER_I18N = {
  'country': i18n('Country'),
  'platform': i18n('Platform'),
  'referer': i18n('Referrer')
};

const AGGREGATION_X_AXIS_FORMAT = {
  [AGGREGATION_DAILY]: 'MM/DD/YY',
  [AGGREGATION_HOURLY]: 'ddd, hA'
};

export default EmberObject.extend({

  init() {
    let hourlyCutoff = moment(this.today).subtract(HOURLY_AGGREGATION_CUTOFF, 'hours');
    this.hourlyAggregationCutoff = hourlyCutoff;
    this.timeSeriesAggregations = parseTimeSeriesData(this.data);

    this.set('selectedMetric', DEFAULT_METRIC);
    this.set('selectedFilter', '');
    this.set('startDate', hourlyCutoff.toDate());
    this.set('endDate', new Date());
  },

  selectedFilterDisplay: computed('selectedFilter', function() {
    let selectedFilter = this.get('selectedFilter');
    return selectedFilter !== '' ? FILTER_I18N[selectedFilter] : '';
  }),

  aggregationMode: computed('startDate', function() {
    let startDate = this.get('startDate');
    let isAfterCutoff = moment(startDate).isSameOrAfter(this.hourlyAggregationCutoff, 'hour');

    return isAfterCutoff ? AGGREGATION_HOURLY : AGGREGATION_DAILY;
  }),

  timeSeries: computed('aggregationMode', function() {
    let timeSeries = this.timeSeriesAggregations[this.get('aggregationMode')];
    return timeSeries ? timeSeries : new TimeSeries();
  }),

  metricOptions: computed('timeSeries', function() {
    return this.get('timeSeries').listChildNodeLabelsFor('').map(metricLabel => {
      return { display: METRIC_I18N[metricLabel], value: metricLabel };
    });
  }),

  filterOptions: computed('timeSeries', 'selectedMetric`', function() {
    let timeSeries = this.get('timeSeries');
    let selectedMetric = this.get('selectedMetric');

    return timeSeries.listChildNodeLabelsFor([selectedMetric]).map(filterLabel => {
      return { display: FILTER_I18N[filterLabel], value: filterLabel };
    });
  }),

  timeSeriesQuery: computed('aggregationMode', 'timeSeries', 'startDate', 'endDate', 'selectedFilter', 'selectedMetric', function() {
    let params = {
      startTime: this.get('startDate'),
      endTime: this.get('endDate'),
      metric: this.get('selectedMetric'),
      respectTimeZones: this.get('aggregationMode') === AGGREGATION_HOURLY
    };

    let filterKey = this.get('selectedFilter');
    if (filterKey) {
      params.filter = { key: filterKey, limit: 5 };
    }

    return this.get('timeSeries').query(params);
  }),

  summaryTableTitle: computed('selectedMetric', 'selectedFilter', function() {
    let selectedFilter = this.get('selectedFilter');
    return selectedFilter !== '' ? FILTER_I18N[selectedFilter] : '';
  }),

  /**
   * Convert the timeSeriesQuery into an object for Chart.js consumption.
   */
  chartDataSets: computed('timeSeriesQuery', 'aggregationMode', function() {
    let aggregationMode = this.get('aggregationMode');
    let xAxisFormat = AGGREGATION_X_AXIS_FORMAT[aggregationMode];

    let chartObject = {};
    this.get('timeSeriesQuery').forEach(dataset => {
      let items = dataset.items.map(item => {
        let time = moment.utc(item.timeStamp);
        if (aggregationMode === AGGREGATION_HOURLY) {
          time.local();
        }

        return {
          x: time.format(xAxisFormat),
          y: item.value
        };
      });

      chartObject[dataset.key] = items;
    });

    return chartObject;
  })
});
