/* globals Twitch, _ */

import Route from 'ember-route';
import injectService from 'ember-service/inject';
import DeprecatedGameModel from 'web-client/models/deprecated-game';
import { CSGO, CREATIVE, GAME_NOT_FOUND } from 'web-client/utilities/game-names';

export default Route.extend({
  clips: injectService(),
  vodGameInfo: injectService(),
  languageDirectoryFilter: injectService(),
  api: injectService(),
  gameSettings: injectService(),
  navigation: injectService(),

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

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

  model(params) {
    let name = params.game_id;

    return DeprecatedGameModel.findByName(this.get('api'), name);
  },

  afterModel(model) {
    this._super(...arguments);
    let gameName = model.get('id');

    this.set('languageDirectoryFilter.gameName', gameName);

    if (gameName === GAME_NOT_FOUND) {
      let url = this.get('router.url');
      this.transitionTo('404', url.slice(1, url.length));
      return;
    }

    // if the `game_id` param does not match the game
    // being rendered, redirect to correct the URL
    //
    // this fixes an issue when navigating to a game with
    // incorrect case
    let params = this.paramsFor(this.routeName);
    let name = params.game_id;
    if (gameName !== name) {
      switch (gameName) {
      case CSGO:
        this.transitionTo('directory.csgo.channels');
        break;
      case CREATIVE:
        this.transitionTo('directory.creative');
        break;
      default:
        this.transitionTo('directory.game', model);
      }
    }

    if (gameName === 'Programming') {
      this.transitionTo('directory.creative.hashtag', 'programming');
    } else if (gameName === 'Game Development') {
      this.transitionTo('directory.creative.hashtag', 'gamedev');
    }

    this.get('gameSettings').getGameSettings(gameName).then(detailsEnabled => {
      this.controllerFor('directory.game').set('isFlGame', detailsEnabled);
    });
  },

  buildPageTitle() {
    let gameModel = this.modelFor(this.routeName);

    return {
      title: `${gameModel.id} - Watch Live Streams on Twitch`,
      hasTwitchTitleSuffix: false
    };
  },

  trackPageView: function (properties) {
    Twitch.tracking.funnel.trackPageView(_.defaults(properties, {
      game: this.controllerFor('directory.game').get('content.id')
    }));
  },

  activate: function () {
    this.get('navigation').setSelected('Games');
  },

  actions: {
    dismissClipsGameUpsell() {
      this.get('clips').dismissGameUpsell();
    }
  }
});
