/* globals Twitch, onPopoutClose */
import computed from 'ember-computed';
import Component from 'ember-component';
import injectService from 'ember-service/inject';
import { windowOpen, locationRedirect } from 'web-client/utilities/redirect';

import {
  BASE_URL as learnMoreUrl,
  CONTENT_CODE_URL as landingUrl,
  CONTENT_CODE_LINKING_URL as linkingUrl,
  SUPPORT as supportUrl
} from 'web-client/utilities/urls/fuel';

export default Component.extend({
  store: injectService(),
  notify: injectService(),
  session: injectService(),
  claimOffer: injectService(),
  premiumGeo: injectService(),
  tracking: injectService(),

  windowOpen,
  locationRedirect,
  landingUrl,
  learnMoreUrl,
  supportUrl,

  // Provided by parent
  gameDetail: null,
  offers: null,
  offer: null,
  broadcasterId: null,
  broadcasterName: null,

  // Flags for showing different parts of the UI... we hide everything by default.
  showFreeWithPrime: false,
  showFreeWithPrimeTrial: false,
  showPrimeNotAvailable: false,
  showOr: false,
  showBuyThisGame:false,
  isClaimingOffer: false,

  linkingUrl: computed('linkingUrl', 'window.location.pathname', function() {
    let redirectRoute = btoa(window.location.pathname.substring(1));
    return `${linkingUrl}&redirectRoute=${redirectRoute}`;
  }),

  checkoutDestinationUrl: computed('gameDetail.actionDetails.destination_url', 'broadcasterId', function () {
    if (this.get('broadcasterId')) {
      return `${this.get('gameDetail.actionDetails.destination_url')}&br_id=${this.get('broadcasterId')}`;
    }
    return this.get('gameDetail.actionDetails.destination_url');
  }),

  didReceiveAttrs() {
    // We probably want to show different things any time the game or offer changes.
    this.figureOutWhatToShow();
  },

  /**
   * This is kinda gross, but it's better for this to be in code than in the templates, where it had been.
   */
  figureOutWhatToShow(){
    let { isAuthenticated, userData } = this.get('session');
    let hasPrime = isAuthenticated && userData.has_premium;
    let isPrimeAvailable = this.get('premiumGeo.showPrimeContent');
    let hasPrimeOffer = !!this.get('offer');

    let showFreeWithPrime = hasPrimeOffer && hasPrime;
    let showFreeWithPrimeTrial = hasPrimeOffer && !hasPrime && isPrimeAvailable;
    let showPrimeNotAvailable = hasPrimeOffer && !hasPrime && !isPrimeAvailable;
    let showBuyThisGame = this.get('gameDetail.isForSale');
    let showOr = hasPrimeOffer && showBuyThisGame;
    let showNotAvailable = !hasPrimeOffer && !showBuyThisGame;

    this.setProperties({showFreeWithPrime, showFreeWithPrimeTrial, showPrimeNotAvailable,
      showOr, showBuyThisGame, showNotAvailable});

  },

  actions: {
    claimOffer(){
      this.set('isClaimingOffer', true);

      let offerId = this.get('offer.id');

      this.get('claimOffer').claim(offerId)
        .then(data => {
          if (this.isDestroyed) { return; }

          if(data.type === 'DIRECT_ENTITLEMENT') {
            this.set('isClaimingOffer', false);

            let href = `/directory/game/${this.get('gameDetail.product.game_id')}/details?redeemed=true`;
            return this.locationRedirect(href);
          }
        })
        .finally(() => {
          if (this.isDestroyed) { return; }
          this.set('isClaimingOffer', false);
        });
    },

    buyGame(){
      let { userData } = this.get('session');
      let login = userData ? userData.login : undefined;
      let id = userData ? userData.id : undefined;
      let eventData = {
        login: login,
        user_id: id,
        device_id: Twitch.idsForMixpanel.getOrCreateUniqueId(),
        client_time: new Date().getTime(),
        location: 'game_detail',
        game_id: this.get('gameDetail.product.game_id'),
        game_name: this.get('gameDetail.product.title'),
        developer: this.get('gameDetail.product.developer_name'),
        genre: this.get('gameDetail.product.genres'),
        asin: this.get('gameDetail.product.asin'),
        channel: this.get('broadcasterName')
      };

      this.get('tracking').trackEvent({
        event: 'fuel_buy_button',
        data: eventData
      });

      let buyPopout = this.windowOpen(this.get('checkoutDestinationUrl'), 'Twitch', 'width=1024,height=700,scrollbars=yes');

      onPopoutClose(buyPopout, () => {
        return this.reloadPage();
      });
    }
  },

  reloadPage() {
    window.location.reload();
  }
});
