import env from 'web-client/config/environment';
import Route from 'ember-route';
import RSVP from 'rsvp';
import injectService from 'ember-service/inject';
import injectScript from 'web-client/utilities/inject-script';

export default Route.extend({
  bits: injectService(),
  bounties: injectService(),
  gameSettings: injectService(),
  _amendmentAccepted: null,
  _requiresServicesTax: null,

  beforeModel(transition) {
    if (!this._super(...arguments)) { return; }

    let user = this.modelFor('user');
    let channelSettingsPromise = this.get('bits').getChannelSettings(user._id);
    let gameCommerceInfo = this.get('bounties').getGameCommerceAmendmentAcceptance(user._id);
    return RSVP.hash({
      channel: channelSettingsPromise,
      bounties: gameCommerceInfo
    }).then(({channel, bounties}) => {
      if (this.isDestroyed) { return; }
      // TODO: Move from Bits service check to Revenue's
      this._requiresServicesTax = !channel.has_services_record;
      this._amendmentAccepted = bounties.amendment_accepted;
    }, () => {
      if (this.isDestroyed) { return; }

      transition.abort();

      return this.intermediateTransitionTo('404', {});
    }).then(() => {
      if (this.get('gameSettings.isFlWhitelisted')) {
        return injectScript(`${env.remoteHostports.FEATURES_FILEPATH}/game-commerce.js`);
      }
    });
  },

  model() {
    let user = this.modelFor('user');

    return RSVP.hash({
      product: this.store.findRecord('product', this.modelFor('dashboards').id),
      amendmentAccepted: this._amendmentAccepted,
      requiresServicesTax: this._requiresServicesTax,
      user: user
    });
  }
});
