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

export const SECOND_IN_MS = 1000;
export const MINUTE_IN_MS = SECOND_IN_MS * 60;
export const HOUR_IN_MS = MINUTE_IN_MS * 60;
export const DAY_IN_MS = HOUR_IN_MS * 24;

export default Component.extend({
  classNames: ['countdown-timer'],

  init() {
    this._super(...arguments);
    this.pollTask('_updateTime', 'countdown-timer');
  },

  now() {
    return new Date();
  },

  interval: SECOND_IN_MS,

  _updateTime(next) {
    this.set('currentTime', this.now());
    this.runTask(next, this.interval);
  },

  endDateAsDate: computed('endDate', function () {
    return new Date(this.get('endDate'));
  }),

  distance: computed('endDateAsDate', 'currentTime', function () {
    return this.get('endDateAsDate') - this.get('currentTime');
  }),

  days: computed("distance", function () {
    return Math.max(0, Math.floor(this.get('distance') / DAY_IN_MS));
  }),

  hours: computed("distance", function () {
    return Math.max(0, Math.floor((this.get('distance') % DAY_IN_MS) / HOUR_IN_MS));
  }),

  minutes: computed("distance", function () {
    return Math.max(0, Math.floor((this.get('distance') % HOUR_IN_MS) / MINUTE_IN_MS));
  }),

  seconds: computed("distance", function () {
    return Math.max(0, Math.floor((this.get('distance') % MINUTE_IN_MS) / SECOND_IN_MS));
  })
});
