/* globals i18n */
import Component from 'ember-component';
import moment from 'moment';

export const DATERANGE_OPTIONS = [
  {
    value: '48hours',
    text: i18n('Last 48 Hours'),
    startDaysAgo: 2,
    endDaysAgo: 0
  },
  {
    value: 'thisWeek',
    text: i18n('Last 7 Days'),
    startDaysAgo: 7,
    endDaysAgo: 0
  },
  {
    value: 'lastWeek',
    text: i18n('Previous Week'),
    startDaysAgo: 14,
    endDaysAgo: 7
  },
  {
    value: '28days',
    text: i18n('Last 28 Days'),
    startDaysAgo: 28,
    endDaysAgo: 0
  }
];

export const MAX_DAYS_AGO = 90;

export default Component.extend({
  dateRangeOptions: DATERANGE_OPTIONS,
  classNames: ['flex', 'flex--verticalCenter'],

  init() {
    this._super(...arguments);
    this.set('isCustomRange', false);
    let maxDaysAgo = moment(this.today).subtract(MAX_DAYS_AGO, 'days');
    if (this.minimumDate) {
      let minDate = moment(this.minimumDate);
      if (minDate.isBefore(maxDaysAgo)) {
        this.minimumDate = maxDaysAgo.toDate();
      } else {
        this.minimumDate = minDate.toDate();
      }
    } else {
      this.minimumDate = maxDaysAgo.toDate();
    }
  },

  didInsertElement() {
    this.setDateRange(this.dateRangeOptions[0]);
  },

  setDateRange(range) {
    this.set('selectedDateRange', range);
    let oldStartDate = this.get('startDate');
    let oldEndDate = this.get('endDate');

    let newStartDate = moment(this.today).subtract(range.startDaysAgo * 24, 'hour');
    if (!newStartDate.isSame(oldStartDate, 'hour')) {
      this.sendAction('setStartDate', newStartDate.toDate());
    }

    let newEndDate = moment(this.today).subtract(range.endDaysAgo * 24, 'hour');
    if (!newEndDate.isSame(oldEndDate, 'hour')) {
      this.sendAction('setEndDate', newEndDate.toDate());
    }
  },

  findDateRangeByValue(value) {
    return this.dateRangeOptions.find(option => option.value === value);
  },

  actions: {
    setStartDate(date) {
      if (date !== this.get('startDate')) {
        this.set('isCustomRange', true);
        this.set('selectedDateRange', {});
        this.sendAction('setStartDate', date);
      }
    },
    setEndDate(date) {
      if (date !== this.get('endDate')) {
        this.set('isCustomRange', true);
        this.set('selectedDateRange', {});
        this.sendAction('setEndDate', date);
      }
    },
    setDateRange(value) {
      let dateRange = this.findDateRangeByValue(value);
      this.set('isCustomRange', false);
      this.setDateRange(dateRange);
    }
  }
});
