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

const { on, observer } = Ember;
const ONE_DAY = 24 * 60 * 60 * 1000;

export default Component.extend({
  _initCountdown: on("didInsertElement", function () {
    this._countdown();
  }),

  attributeBindings:['video.randomId:data-id'],

  isExpiring: computed('video.video.delete_at', function () {
    let deleteAt = this.get('video.video.delete_at'),
        oneWeekFromNow = new Date(),
        isHighlight = this.get('isHighlight');

    oneWeekFromNow.setDate(oneWeekFromNow.getDate() + 7);
    return deleteAt && deleteAt < oneWeekFromNow && !isHighlight;
  }),

  deleteDate: computed('video.video.delete_at', 'isExpiring', function () {
    let now = new Date();
    let diffDate = Math.round(this.get('video.video.delete_at') - now);

    // if difference is greater than 24 hours, display as days
    if (this.get('isExpiring')) {
      if (diffDate > ONE_DAY) {
        let days = Math.round(diffDate / ONE_DAY);

        if (days > 1) {
          return `${days} days`;
        }
        return `${days} day`;
      }
      return this.get('video.video.delete_at');
    }
  }),

  isHighlight: computed.equal('video.video.broadcast_type', 'highlight'),

  isCountdown: computed('video.video.delete_at', 'isExpiring', function () {
    let now = new Date();
    let diffDate = Math.round(this.get('video.video.delete_at') - now);
    if (this.get('isExpiring') === true) {
      return diffDate < ONE_DAY;
    }
  }),

  _countdown: observer('video.video.isLoaded', function () {
    if (this.get('isCountdown')) {
      this.runTask(() => {
        let $vodDeleteDate = this.$('.js-vod-delete-date');

        if ($vodDeleteDate) {
          $vodDeleteDate.countdown({
            until: this.get('deleteDate'),
            compact: true,
            description: ''
          });
        }
      });
    }
  }),

  actions: {
    removeVideo: function (video) {
      this.sendAction("removeVideo", video);
    }
  }
});
