/* 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 codeLinkingUrl
} from 'web-client/utilities/urls/fuel';

export default Component.extend({
  classNames: ['js-game-details-get-game-offer'],

  store: injectService(),
  notify: injectService(),
  session: injectService(),
  claimOffer: injectService(),
  premiumGeo: injectService(),
  tracking: injectService(),

  windowOpen,
  locationRedirect,
  landingUrl,
  learnMoreUrl,
  codeLinkingUrl,

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

  // Flags for showing different parts of the UI... we hide everything by default.
  isGameForSale: false,
  isGameAvailableViaPrime: false,
  isGameUnavailable: false,
  isGameExternallyEntitled: false,

  canClaimViaPrime: false,
  canClaimViaPrimeTrial: false,
  claimViaPrimeUnavailable: false,
  externalEntitlementLink: null,

  isClaimingOffer: false,
  linkingUrl: null,

  checkoutDestinationUrl: computed('gameDetail.actionDetails.destination_url', 'broadcasterId', function () {
    let url = this.get('gameDetail.actionDetails.destination_url');
    let broadcasterId = this.get('broadcasterId');

    if (broadcasterId) {
      url += `&br_id=${broadcasterId}`;
    }
    return url;
  }),

  init() {
    this._super(...arguments);

    let redirectRoute = btoa(window.location.pathname.substring(1));
    this.set('linkingUrl', `${this.get('codeLinkingUrl')}&redirectRoute=${redirectRoute}`);
  },

  didReceiveAttrs() {
    this._super(...arguments);

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

  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, this._reloadPage);
    }
  },

  /**
   * 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 isGameAvailableViaPrime = !!this.get('offer');

    let isGameForSale = this.get('gameDetail.isForSale');
    let isGameUnavailable = !isGameAvailableViaPrime && !isGameForSale;
    let isGameExternallyEntitled = this.get('gameDetail.product.is_externally_entitled');

    let canClaimViaPrime = isGameAvailableViaPrime && hasPrime;
    let canClaimViaPrimeTrial = isGameAvailableViaPrime && !hasPrime && isPrimeAvailable;
    let claimViaPrimeUnavailable = isGameAvailableViaPrime && !hasPrime && !isPrimeAvailable;

    let externalEntitlementLink = this.get('gameDetail.actionDetails.destination_url');

    this.setProperties({
      isGameForSale,
      isGameAvailableViaPrime,
      isGameUnavailable,
      isGameExternallyEntitled,

      canClaimViaPrime,
      canClaimViaPrimeTrial,
      claimViaPrimeUnavailable,

      externalEntitlementLink
    });
  },

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