// import Video from 'web-client/models/video';
import VideoManagerProperties from 'web-client/models/video-manager-properties';
import VodAppeal from 'web-client/models/vod-appeal';
import TrackBttv from 'web-client/mixins/track-bttv';
import FullSizePlayerRoute from 'web-client/routes/full-size-player-route';
import Timer from 'web-client/mixins/timer';
import computed from 'ember-computed';
import RSVP from 'rsvp';
import injectService from 'ember-service/inject';
import getOwner from 'ember-owner/get';
import { normalizeVideoId } from 'web-client/utilities/normalize-video-id';
import { isFollowingColumnInteractive } from 'web-client/utilities/interactivity';

const PROFILE_MEDIUM = 'twitch_profile';

export default FullSizePlayerRoute.extend(Timer, TrackBttv, {
  globals: injectService(),
  badges: injectService(),
  layout: injectService(),
  watchedChannels: injectService(),
  watchedGames: injectService(),
  vodGameInfo: injectService(),
  session: injectService(),

  isVodAppealsEnabled: computed.alias('globals.isVodAppealsEnabled'),
  channel: null,
  ttLocation: 'vod',

  isInteractive(interactiveComponents) {
    return interactiveComponents['persistent-player'] && (
      interactiveComponents['video/rechat/display-container'] || isFollowingColumnInteractive(interactiveComponents)
    );
  },

  activate() {
    this._super(...arguments);
    this.set('layout.showRightColumn', true);
  },

  deactivate() {
    this.set('layout.showRightColumn', false);
    this._super(...arguments);
  },

  beforeModel(transition) {
    this._super(...arguments);
    if (transition.queryParams.medium === PROFILE_MEDIUM) {
      this.set('medium', PROFILE_MEDIUM);
    }

    return this.get('vodGameInfo').checkExperiment();
  },

  model(params) {
    let videoId = normalizeVideoId(params.video_id);

    let videoPromise = this.get('store').findRecord('video', videoId).then(undefined, () => {
      return {
        id: videoId,
        notFound: true
      };
    });

    let channelPromise = videoPromise.then((video) => {
      if (video.notFound) {
        return null;
      }
      return video.get('channel').then((channel) => {
        this.set('channel', channel);
        return this.get('channel');
      }, () => {
        // If the video exists but the channel doesn't exist, the channel must have been deleted.
        video.set('notFound', true);
        video.set('unavailable', true);
        return null;
      });
    });

    /* eslint-disable no-unused-vars */
    return RSVP.hash({
      channel: channelPromise,
      video: videoPromise
    }).then(({channel, video}) => {
      video.collection = params.collection;
      return video;
    });
    /* eslint-enable no-unused-vars */
  },

  afterModel(video) {
    this._super(...arguments);
    if (video.collection) {
      this.send('setCollection', video.collection);
    }

    if (video.notFound) {
      return;
    }

    this.send('setPlayerVOD', video);
    this.get('badges').updateChannelBadges(this.channel.get('_id'), this.channel.get('id'));

    let { isAuthenticated, userData } = this.get('session');
    if (!isAuthenticated || userData.login !== video.get('channel.id')) {
      return;
    }

    let promises = [];
    let propertiesPromise = VideoManagerProperties.findOne(this.channel.get('name')).load(true).then((properties) => {
      video.set('youtubeConnected', properties.get('youtube_connected'));
      video.set('liveAnnotationsEnabled', properties.get('live_annotations_enabled'));
    });

    promises.push(propertiesPromise);

    if (this.get('isVodAppealsEnabled')) {
      // Preload and cache
      promises.push(VodAppeal.find(getOwner(this), video.id));
    }

    return RSVP.all(promises);
  },

  // called by the Timer mixin
  _timesUp() {
    let watchedChannelService = this.get('watchedChannels');
    let watchedGamesService = this.get('watchedGames');
    let video = this.modelFor(this.routeName);

    if (video.notFound) {
      return;
    }

    watchedChannelService.addChannel(this.channel.get('name'));
    watchedGamesService.addGame(video.game);
  },

  buildPageTitle() {
    const video = this.modelFor(this.routeName);
    const channel = this.channel;
    let creatorName = channel ? channel.get('displayName') : null;
    return {
      title: video.notFound ? null : creatorName
    };
  },

  serialize(video) {
    return { video_id: normalizeVideoId(video.get('id')) };
  }
});
