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

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

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

  defaultSortOption: SORT_PERIOD_WEEK,
  clipsSortOption: SORT_PERIOD_WEEK,
  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.isClipsTabEnabled')) {
      this.replaceWith('channel.index');
    }
  },

  model() {
    let channelName = this.modelFor('user').get('name');
    let channel = this.modelFor('channel');
    let params = this.get('clipsParams');
    let clips = this.get('store').findRecord('channel', channelName).then(channelModel => {
      let clipsPaginator = this.get('paginator').paginatorFor({
        model: channelModel,
        relationshipName: 'clips',
        pageFactory: 'clip',
        params: assign({}, params, { channel: channelName })
      });

      // 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,
      channel,
      sortOption,
      popularSortOption: SORT_PERIOD_ALL
    });
  },

  activate() {
    // Dismiss upsell -- they're already on the Clips route!
    this.get('clips').dismissUpsell();
  },

  deactivate() {
    // Set default sort option here since route instances persist and will save the latest sort option
    this.set('clipsSortOption', this.get('defaultSortOption'));
  },

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