import Model from 'ember-data/model';
import attr from 'ember-data/attr';
import computed from 'ember-computed';

const VIEW_COUNT = 'viewcount';
const MINUTES_WATCHED = 'minuteswatched';
const AVERAGE_DURATION = 'averageviewduration';

export default Model.extend({
  analytics: attr(),

  averageDuration: computed('analytics', function() {
    return this.getAnalyticValue(AVERAGE_DURATION);
  }),

  minutesWatched: computed('analytics', function() {
    return this.getAnalyticValue(MINUTES_WATCHED);
  }),

  viewCount: computed('analytics', function() {
    return this.getAnalyticValue(VIEW_COUNT);
  }),

  getAnalytic(type) {
    let analytics = this.get('analytics');
    if (!analytics) {
      return {};
    }

    return analytics.find(analytic => analytic.metric === type);
  },

  getAnalyticValue(type) {
    let analytic = this.getAnalytic(type);
    return analytic.metric_data ? analytic.metric_data : 0;
  },

  getAnalyticsByFilter(filterType) {
    let analytics = this.get('analytics');
    let rowsByKey = {};
    let rows = [];

    analytics.forEach(analytic => {
      let filter = analytic.filter_data[filterType];
      if (!filter) {
        return;
      }

      Object.keys(filter).forEach(key => {
        if (!rowsByKey[key]) {
          let row = { key: key };
          rowsByKey[key] = row;
          rows.push(row);
        }

        rowsByKey[key][analytic.metric] = filter[key];
      });
    });

    return rows;
  }
});
