/* globals Twitch, SiteOptions, i18n */

import get from 'ember-metal/get';
import injectService from 'ember-service/inject';
import Route from 'ember-route';
import RSVP from 'rsvp';
import { assign } from 'ember-platform';
import { CHANNELS, VODS } from 'web-client/components/tag-streams';

export default Route.extend({
  communityService: injectService('community'),
  store: injectService(),
  tmi: injectService(),

  queryParams: {
    period: {
      refreshModel: true
    },
    broadcasterLanguage: {
      refreshModel: true
    }
  },

  broadcasterLanguage: null,
  tag: null,

  resetController(controller, isExiting) {
    if (isExiting) {
      controller.set('period', 'month');
    }
  },

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

    let tag = transition.params['directory.creative.hashtag'].tag;
    if (this.get('communityService').isBannedCommunity(tag)) {
      throw new Error('Invalid Community');
    }
    // hack to support localized directories we implicitly
    // ban all language codes as communities by doing this
    let broadcasterLanguage = null;
    if (SiteOptions.broadcaster_languages[tag]) {
      broadcasterLanguage = tag;
      tag = null;
    }
    this.setProperties({tag, broadcasterLanguage});
  },

  model(params) {
    let parentModel = this.modelFor('directory.creative');
    let broadcasterLanguage = this.get('broadcasterLanguage') || null;
    let communities = parentModel.tags.filterBy('isCommunity');
    let currentPeriod = params.period || null;
    let tag = this.get('tag');
    let currentTag = tag ? this.getCommunity(tag, parentModel.game) : this.get('store').createRecord('community', { name: 'all' });
    let channels = parentModel.channels;
    return RSVP.hash({
      broadcasterLanguage,
      channels,
      communities,
      currentPeriod,
      currentTag,
      game: parentModel.game,
      streamTypes: { CHANNELS, VODS }
    });
  },

  getCommunity(name, game) {
    return this.get('store').queryRecord('community', { community: name, game: game.get('name') })
      .catch(err => {
        // If no record is found we _fake_ a new model as there is currently no such
        // thing as a non-existing Community, just a community with no streams
        if (err.status === 400 || err.status === 404) {
          return this.get('store').createRecord('community', { name });
        }
        throw new Error('Invalid Community');
      });
  },

  buildPageTitle() {
    let communityModel = this.modelFor(this.routeName);
    let currentTag = get(communityModel, 'currentTag.name');
    let title = i18n('Creative');

    if (currentTag) {
      title = `${currentTag.capitalize()} - ${title}`;
    }

    return { title };
  },

  trackPageView(properties) {
    let tag = this.get('controller.model.currentTag.name') || null;
    Twitch.tracking.funnel.trackPageView(assign(properties, {
      hashtag: tag,
      game: 'Creative'
    }));
  }
});
