/* globals i18n */

import $ from 'jquery';
import Ember from 'ember';
import Route from 'ember-route';
import injectService from 'ember-service/inject';
import urlParams from 'web-client/utilities/url-params';

const { Logger } = Ember;

// TODO: Change route to a more meaningful name after launch
export default Route.extend({
  layout: injectService(),
  session: injectService(),
  geo: injectService('premium-geo'),

  // If the user is not in a prime region, redirect to the home page
  beforeModel(transition) {
    this._super(...arguments);

    let { userData } = this.get('session');
    return this.get('geo').getPrimeGeoPromise().then(isPrimeGeo => {
      if ((!userData || !userData.has_premium) || !isPrimeGeo) {
        transition.abort();
        this.transitionTo('index');
      }
    });
  },

  /**
   * This is not used as a component, but it will be brought back into the view
   * template after launch
   */
  buildPageTitle() {
    return {
      title: i18n('Welcome to Twitch Prime'),
      hasTwitchTitleSuffix: false
    };
  },

  activate() {
    this.set('layout.bypassApplicationLayout', true);
    $('body').addClass('pr-welcome__scrollbar-body');
  },

  deactivate() {
    this.set('layout.bypassApplicationLayout', false);
    $('body').removeClass('pr-welcome__scrollbar-body');
  },

  actions: {
    goToRedirectRouteWithOffers() {
      if (urlParams.redirectRoute) {
        try {
          window.location = `/${atob(urlParams.redirectRoute)}?expandoffers=true`;
          return;
        }
        catch(e) {
          Logger.error('Failed to base64 decode parameter', urlParams.redirectRoute);
        }
      }
      window.location = '/directory/following?expandoffers=true';
    },

    goToRedirectRouteWithSubModal() {
      if (urlParams.redirectRoute) {
        try {
          window.location = `/${atob(urlParams.redirectRoute)}?expandsubmodal=true`;
          return;
        }
        catch(e) {
          Logger.error('Failed to base64 decode parameter', urlParams.redirectRoute);
        }
      }
      window.location = '/directory/following';
    }
  }

});
