import Component from 'ember-component';
import computed from 'ember-computed';
import moment from 'moment';

const DEFAULT_SAME_YEAR_FORMAT = 'MMM D, YYYY';
const DEFAULT_DIFFERENT_YEAR_FORMAT = 'MMM D, YYYY';

let RelativeTime = Component.extend({
  tagName: 'span',
  classNames: ['balloon-wrapper'],

  absoluteFormat: 'MMM D, YYYY',
  alwaysAbsolute: false,
  date: null,
  differentYearFormat: DEFAULT_DIFFERENT_YEAR_FORMAT,
  relativeDayCutoff: 1,
  sameYearFormat: DEFAULT_SAME_YEAR_FORMAT,
  showTooltip: false,
  tooltipDirection: 'down',

  dateString: computed('date', function() {
    let date = this.get('date');
    let relativeDayCutoff = this.get('relativeDayCutoff') || 1;

    if (typeof date === 'number') {
      date = moment.unix(date);
    } else {
      date = moment(date);
    }

    let now = moment();
    if (now.diff(date, 'days') >= relativeDayCutoff) {
      let isSameYear = now.year() === date.year();
      let absoluteFormat = isSameYear ? this.get('sameYearFormat') : this.get('differentYearFormat');
      return date.format(absoluteFormat);
    }

    return date.fromNow();
  })
});

RelativeTime.reopenClass({
  positionalParams: ['date']
});

export default RelativeTime;
