/* globals i18n */

import Ember from 'ember';
import Component from 'ember-component';
import YoutubeExporterMixin from 'web-client/mixins/youtube-exporter';
import SendRouteActionMixin from 'web-client/mixins/send-route-action';
import VodAppeal from 'web-client/models/vod-appeal';
import computedEqualProperty from 'web-client/utilities/computed-equal-property';
import computed from 'ember-computed';
import injectController from 'web-client/utilities/inject-controller';
import injectService from 'ember-service/inject';
const { getOwner } = Ember;

export default Component.extend(YoutubeExporterMixin, SendRouteActionMixin, {
  globals: injectService(),
  session: injectService(),
  manager: injectController(),
  application: injectController(),
  notify: injectService(),

  content: null,
  showDropdown: false,
  isCountdown: null,
  isPastBroadcasts: false,

  isVodAppealsEnabled: computed.alias('globals.isVodAppealsEnabled'),
  video: computed.alias('content'),
  canAppeal: computed.and('video.is_muted', 'isVodOwner', 'isVodAppealsEnabled', 'isPastBroadcasts'),

  // Decide whether to display an appeal form modal or a mailto link.
  canAppealWithForm: computed.reads('canAppeal'),

  appealPending: computed.alias('vodAppeal.hasPendingAppeal'),
  isVodOwner: computedEqualProperty('session.userData.login', 'video.channel.name'),

  appealHref: computed('video.url', function() {
    let urlParam = encodeURIComponent(this.get('video.url'));
    return `mailto:contentappeals@twitch.tv?subject=${urlParam}`;
  }),

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

    oneWeekFromNow.setDate(oneWeekFromNow.getDate() + 7);

    return deleteAt && deleteAt < oneWeekFromNow;
  }),

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

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

        return `${dayCount} ${daysUnit}`;
      }

      this.set('isCountdown', true);

      return this.get('video.delete_at');
    }
  }),

  /**
   * A user can always export videos from their own channel. However, when viewing another's'
   * channel, video's cannot be exported if the youtube_exporting_disabled flag is on.
   */
  canExportVideos: computed(function() {
    let isChannelOwner = this.get('video.channel.name') === this.get('session.userData.login');
    return isChannelOwner || !this.get('video.videoManagerProperties.youtube_exporting_disabled');
  }),

  init() {
    this._super(...arguments);

    if (this.get('canAppealWithForm')) {
      this.set('vodAppeal', VodAppeal.find(getOwner(this), this.get('video.id')));
    }
  },

  didInsertElement() {
    this._super(...arguments);

    this._initDropmenuOptions();
    this._initCountdown();
  },

  _initDropmenuOptions() {
    this.addEventListener('.filter-toggle', 'clickoutside', () => {
      this.set('showDropdown', false);
    });
  },

  _initCountdown() {
    if (this.get('isCountdown')) {
      this.$('.info-overlay .expiration .date').countdown({
        until: this.get('deleteDate'),
        compact: true,
        description: ''
      });
    }
  },

  actions: {
    toggleDropmenu() {
      this.set('showDropdown', !this.get('showDropdown'));
    },

    handleUpdateVideoDelete() {
      let notify = this.get('notify');

      this.get('video').del().then(() => {
        notify.success(i18n('Video successfully deleted'));

        // TODO: Bug: videos aren't removed from UI after they are deleted.
        // self.sendRouteAction('removeVideo', self.content);
      }).catch((response) => {
        let message;

        try {
          message = JSON.parse(response.responseText).message;
        } catch (e) {
          message = 'There was a problem deleting your video';
        }

        notify.error(message);
      });

      this.sendRouteAction('closeModal');
    },

    showVodAppealsForm() {
      this.sendRouteAction('openInModal', 'video/appeals/appeal-modal', this, { model: this.get('video') });
    },

    closeModal() {
      this.sendRouteAction('closeModal');
    }
  }
});
