/* globals Twitch */

import Component from 'ember-component';
import computed from 'ember-computed';
import ClickOutsideMixin from 'web-client/mixins/click-outside';
import injectService from 'ember-service/inject';
import SendRouteActionMixin from 'web-client/mixins/send-route-action';
import YoutubeExporterMixin from 'web-client/mixins/youtube-exporter';
import { reportFormAjax } from 'web-client/utilities/report-form';
import $ from 'jquery';
import moment from 'moment';
import {
  ARCHIVE_TYPE_PARAM,
  HIGHLIGHT_TYPE_PARAM
} from 'web-client/utilities/video/types';
import { normalizeVideoId } from 'web-client/utilities/normalize-video-id';

export default Component.extend(ClickOutsideMixin, SendRouteActionMixin, YoutubeExporterMixin, {
  session: injectService(),
  isMenuOpen: false,
  tagName: "span",
  vodChatService: injectService(),

  willDestroyElement() {
    $('body').teardownOverlay();
    this._super(...arguments);
  },

  _toggleMenu() {
    this.toggleProperty('isMenuOpen');
  },

  clickedOutside() {
    this.set('isMenuOpen', false);
  },

  highlightHref: computed('channel.id', 'video.id', function () {
    return Twitch.uri.highlightVod(this.get("channel.id"), `v${normalizeVideoId(this.get("video.id"))}`);
  }),

  isChannelOwner: computed('channel.id', function () {
    let { isAuthenticated, userData } = this.get('session');
    return isAuthenticated && userData.login === this.get('channel.id');
  }),

  isVodOwner: computed.equal('session.userData.login', 'video.channel.id'),

  isExportable: computed('video.type', 'video.viewer', 'video.viewer.isLoaded', 'video.viewer.is_editor', function () {
    if (this.get('video.viewer') && !this.get('video.viewer.isLoaded')) {
      this.get('video.viewer').load();
    }

    return [ARCHIVE_TYPE_PARAM, HIGHLIGHT_TYPE_PARAM].indexOf(this.get('video.type')) > -1  && this.get('video.viewer.is_editor');
  }),

  canHighlight: computed('video.type', 'video.viewer', 'video.viewer.isLoaded', 'video.viewer.is_editor', function () {
    if (this.get('video.viewer') && !this.get('video.viewer.isLoaded')) {
      this.get('video.viewer').load();
    }

    return this.get('video.type') === ARCHIVE_TYPE_PARAM && this.get('video.viewer.is_editor');
  }),

  actions: {
    report() {
      let reportForm = `/${this.get('channel.id')}/report_form`;
      let timestamp;
      let params = {};

      if (this.get('video')) {
        let currentTime = this.get('vodChatService.lastTickTime');
        let recordedDate = moment.utc(this.get('video.recordedDate')).valueOf();
        let relativeTime = moment.utc(currentTime - recordedDate);
        timestamp = moment.utc(relativeTime).format('HH:mm:ss');

        params.vod_id = `v${normalizeVideoId(this.get('video.id'))}`;
        params.timestamp = timestamp;
      }

      let serializedParams = $.param(params);

      reportForm += `?${serializedParams}`;

      if (!this.get('session').isAuthenticated) {
        $.login({mpSourceAction: "channel-report"});
        return;
      }
      $('body').overlay(
        reportForm,
        reportFormAjax,
        {'width': '420px'}
      );
    },

    openInModal() {
      this.sendRouteAction('openInModal', 'shared/delete_video', this);
    },

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

    handleUpdateVideoDelete() {
      this.get('video.channel').then((channel) => {
        this.get('video').destroyRecord().finally(() => {
          this.sendRouteAction('closeModal');
          window.location = `/${channel.id}/manager/past_broadcasts`;
        });
      });
    },

    toggle() {
      this._toggleMenu();
    }
  }
});
