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

const DETAILS_SIDEBAR_WIDTH = 320;
const DETAILS_SIDEBAR_LEFT_MARGIN = 30;

export default Component.extend({
  classNames: ['details'],
  layout: injectService(),
  store: injectService(),

  // Provided by route & route template
  gameDetail: null,
  broadcasterId: null,
  broadcasterName: null,

  // Set during init (async)
  offer: null, // Direct Entitlement offer for this game

  hasSpaceForSidebar: computed('layout.contentWidth', function() {
    const DETAILS_MIN_WIDTH = 320;
    return (this.get('layout.contentWidth') - DETAILS_SIDEBAR_LEFT_MARGIN - DETAILS_SIDEBAR_WIDTH) >= DETAILS_MIN_WIDTH;
  }),

  init() {
    this._super(...arguments);
    return this.get('store').findAll('offer').then((offers) => {
      if (this.isDestroyed) { return; }
      //TODO: Scotch in the morning? Sure, why not... also, let's not use game names as IDs.
      let gameTitle = this.get('gameDetail.product.title');
      if (gameTitle === "The Walking Dead") {
          gameTitle = "The Walking Dead: Season 1 (WIN)";
      } else if (gameTitle === "The Walking Dead: Season Two") {
          gameTitle = "The Walking Dead: Season 2 (WIN)";
      }

      let offer = offers.find((item) => {
        return item.get('applicableGame').indexOf(gameTitle) === 0;
      }, gameTitle);
      if (offer &&
        offer.get('contentDeliveryMethod') === 'DIRECT_ENTITLEMENT' &&
        offer.get('isLive')) {
        this.set('offer', offer);
      }
    });
  },

  didInsertElement() {
    this.updateCarouselWidth();
  },

  observeDimensions: observer('layout.contentWidth', 'layout.windowHeight', function() {
    this.updateCarouselWidth();
  }),

  // When width or height changes, we want to update the size so the carousel always appears fully above the fold.
  updateCarouselWidth() {
    //                  Margin, title height, margin
    const CAROUSEL_ABOVE_HEIGHT = 30 + 80 + 30;
    const CAROUSEL_MIN_HEIGHT = 240;
    let contentWidth = this.get('layout.contentWidth') - DETAILS_SIDEBAR_LEFT_MARGIN;
    if(this.get('hasSpaceForSidebar')) {
      contentWidth -= DETAILS_SIDEBAR_WIDTH;
    }

    // We want the carousel to have a 4:3 ratio
    let naturalCarouselHeight = contentWidth * 3 / 4;
    let maxPlayerHeight = this.get('layout.windowHeight') - CAROUSEL_ABOVE_HEIGHT;
    let carouselWidth = Math.floor(contentWidth);
    let carouselHeight = Math.floor(Math.max(CAROUSEL_MIN_HEIGHT, Math.min(naturalCarouselHeight, maxPlayerHeight)));
    this.setProperties({
      carouselWidth, carouselHeight
    });

  }
});
