/* globals Twitch */

import Component from 'ember-component';
import injectService from 'ember-service/inject';
import computed from 'ember-computed';

import { TTV_BOXART_404_URL } from 'web-client/utilities/urls/static-cdn';
import {
  SUPPORT as supportUrl
} from 'web-client/utilities/urls/fuel';

export default Component.extend({
  tagName:'',

  store: injectService(),
  gameSettings: injectService(),

  supportUrl,

  channel: null, // Provided by parent
  isHosting: '', // Provided by parent, falsey, not specifically true/false

  channelName: computed.alias('channel.name'),
  channelId: computed.alias('channel._id'),

  showBuyGame: true,
  showBuyPackage: false,
  showSupports: true, // Will eventually be pulled from the server
  gameDetails: null,

  isHidden: computed('gameDetails', 'isHosting', function() {
    // We hide if the channel is hosting another channel.
    if (this.get('isHosting') || !this.get('channel.partner')) {
      return true;
    }
    if (this.get('gameDetails.isForSale')) {
      return false;
    }
    return true;
  }),

  didReceiveAttrs() {
    if(this.get('isHosting')) {
      //If the channel is hosting another channel, we don't bother loading anything
      return;
    }
    let details = this.get('gameDetails');
    if(!details || this.get('channel.game').toLowerCase() !== details.get('product.title').toLowerCase()) {
      this.set('gameDetails', null);
      this.runTask(this._loadGameDetails.bind(this));
    }
  },
  _loadGameDetails() {
    let gameName = this.get('channel.game');
    if (!gameName) {
      // Can't load a game w/ no name
      return;
    }
    // game-detail endpoint has not yet been load-tested for full channel TPS...
    // For now, we only call it if the game is commerce-enabled.
    this.get('gameSettings').getGameSettings(gameName)
      .then((isCommerceEnabled) => {
        if (this.isDestroyed) {
          return;
        }
        if(!isCommerceEnabled) {
          this.set('gameDetails', null);
          return;
        }
        this.get('store').queryRecord('game-detail', {game: gameName})
          .then((details) => {
            if (this.isDestroyed) {
              return;
            }
            if(!details || this.get('channel.game').toLowerCase() === details.get('product.title').toLowerCase()) {
              this.set('gameDetails', details);
            }
          }, () => {
            if (this.isDestroyed) {
              return;
            }
            this.set('gameDetails', null);
          });
      });
  },
  boxArt: computed('channel.game', function() {
    let game = this.get('channel.game');
    let boxart = Twitch.uri.gameBoxArtJpg(game);
    return boxart ? boxart : TTV_BOXART_404_URL;
  }),
  actions: {
    refreshDetails() {
      this._loadGameDetails();
    }
  }
});
