/* globals Twitch, onPopoutClose */

import Component from 'ember-component';
import injectService from 'ember-service/inject';
import computed from 'ember-computed';
import { windowOpen } from 'web-client/utilities/redirect';
import {
  LAUNCHER as launcher
} from 'web-client/utilities/urls/fuel';

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

  launcher,
  windowOpen,

  gameDetails: null, // Injected by parent component.
  channelName: null,
  channelId: null,

  // Closure Action, injected by parent
  // Executed after any possible entitlement changes have taken place
  entitlementChanged: null,

  classNames: ["flex", "flex--nowrap", "flex__item", "flex__item--grow", "flex__item--noShrink"],

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

  actions:{
    trackGetLauncher() {
      let eventData = {
        login: this.get('session.userData.login'),
        user_id: this.get('session.userData.id'),
        device_id: Twitch.idsForMixpanel.getOrCreateUniqueId(),
        client_time: new Date().getTime(),
        location: 'channel',
        game: this.get('gameDetail.product.title'),
        channel: this.get('channelName'),
        urls: this.get('launcher')
      };

      this.get('tracking').trackEvent({
        event: 'fuel_download_launcher',
        data: eventData
      });
    },
    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: 'channel',
        game_id: this.get('gameDetails.product.game_id'),
        game_name: this.get('gameDetails.product.title'),
        developer: this.get('gameDetails.product.developer_name'),
        genre: this.get('gameDetails.product.genres'),
        asin: this.get('gameDetails.product.asin'),
        channel: this.get('channelName')
      };

      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.entitlementChanged();
      });
    }
  }
});
