/* globals Twitch */

import Timer from 'web-client/mixins/timer';
import FullSizePlayerRoute from 'web-client/routes/full-size-player-route';
import { assign as merge } from 'ember-platform';
import injectService from 'ember-service/inject';
import RSVP from 'rsvp';

export default FullSizePlayerRoute.extend(Timer, {
  // NOTICE: The login service is deprecated, plesase use the session service.
  // See app/services/SESSION.md for more details.
  login: injectService(),
  watchedChannels: injectService(),
  watchedGames: injectService(),
  experiments: injectService(),
  tracking: injectService(),
  persistentPlayer: injectService(),
  navigation: injectService(),

  controllerName: 'channel',
  ttLocation: 'channel',

  trackPageView: function (properties) {
    Twitch.tracking.funnel.trackPageViewWithDiagnostics(
      RSVP.hash({
        isLive: this.controllerFor('channel').get('isLivePromise'),
        follow: this.getIsFollowingPromise()
      }).then(results => {
        let user = this.modelFor('user');

        return merge({
          is_live: results.isLive,
          is_following: results.follow && results.follow.get('isFollowing'),
          channel: user.get('id'),
          game: user.get('game')
        }, properties);
      })
    );
  },

  getIsFollowingPromise: function () {
    if (Twitch.user.isLoggedIn()) {
      let channel = this.modelFor('channel').get('id');
      return this.store.findRecord('follow', channel);
    }
    return RSVP.resolve(null, 'ChannelIndexRoute#getIsFollowingPromise');
  },

  model() {
    return this.modelFor('channel');
  },

  afterModel() {
    let channel = this.controllerFor('channel').get('channelModel');
    this.send('setPlayerStream', channel);
    this.get('tracking.benchmark').track('after_model', {ttLocation: this.get('ttLocation')});
    this._super(...arguments);
  },

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

    watchedChannelService.addChannel(model.id);
    watchedGamesService.addGame(model.game);
  },

  activate: function () {
    if (this.get('login.userData.login') === this.model().id) {
      this.get('navigation').setSelected('Channel');
    } else {
      this.get('navigation').setSelected();
    }
  },


  actions: {
    willTransition() {
      this.send('closeModal');
      this._super(...arguments);
      return true;
    },

    openPost(post) {
      this.transitionTo('channel.index.post', post);
    }
  }
});
