/* globals Twitch */
import Route from 'ember-route';
import computed from 'ember-computed';
import injectService from 'ember-service/inject';
import { assign } from 'ember-platform';
import RSVP from 'rsvp';
import { SORT_PERIOD_ALL, SORT_PERIOD_DAY, SORT_TRENDING } from 'web-client/adapters/clip';
import { CSGO } from 'web-client/utilities/game-names';

export const CLIPS_HELP_ARTICLE = 'https://help.twitch.tv/customer/portal/articles/2442508-how-to-use-clips';
export const CLIPS_TRACKING_LOCATION = 'clips_game';

export default Route.extend({
  clips: injectService(),
  paginator: injectService(),

  defaultSortOption: SORT_PERIOD_DAY,
  clipsSortOption: SORT_PERIOD_DAY,
  clipsParams: computed('clipsSortOption', function() {
    let sortOption = this.get('clipsSortOption');
    let trending = (sortOption === SORT_TRENDING);
    let period = trending ? SORT_PERIOD_ALL : sortOption;

    return { period, trending };
  }),

  trackPageView: function (properties) {
    Twitch.tracking.funnel.trackPageView(assign({}, properties, {
      location: CLIPS_TRACKING_LOCATION
    }));
  },

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

    if (!this.get('clips.isClipsTabOnGameDirEnabled')) {
      this.replaceWith('directory.csgo.videos');
    }
  },

  model() {
    let gameName = CSGO;
    let game = this.get('store').findRecord('game', gameName);
    let params = this.get('clipsParams');

    let clips = this.get('store').findRecord('game', gameName).then(gameModel => {
      let clipsPaginator = this.get('paginator').paginatorFor({
        model: gameModel,
        relationshipName: 'clips',
        pageFactory: 'clip',
        params: assign({}, params, { game: gameName })
      });

      // Fetch initial set of Clips (infinite-scroll does not guarantee content population on initialization)
      clipsPaginator.fetchNextPage();

      return clipsPaginator;
    });

    let sortOption = this.get('clipsSortOption');

    return RSVP.hash({
      clips,
      game,
      sortOption,
      popularSortOption: SORT_PERIOD_ALL
    });
  },

  actions: {
    changeClipsSortOption(sortOption) {
      this.set('clipsSortOption', sortOption);
      this.refresh();
    },
    popularSortOption() {
      this.set('clipsSortOption', SORT_PERIOD_ALL);
      this.refresh();
    }
  }
});
