import Component from 'ember-component';
import computed from 'ember-computed';
import injectService from 'ember-service/inject';
import $ from 'jquery';
import { htmlSafe } from 'ember-string';

const SWITCH_TO_THUMBNAIL_OFFSET = 150;

export default Component.extend({
  playerRegistry: injectService(),
  scrollActivity: injectService(),

  thumbnailMode: true,
  thumbnailEventID: computed('elementId', function () {
    return `thumbnail.${this.elementId}`;
  }),

  iframeHTML: computed('embed.player_html', function () {
    return htmlSafe(this.get('embed.player_html'));
  }),

  embedEl: computed(function () {
    return this.$()[0];
  }),

  init() {
    this._super(...arguments);
    this._subscribeToAutoplay();
  },

  willDestroyElement() {
    this._super(...arguments);
    if (this.get('thumbnailMode') === false) {
      this.get('scrollActivity').unsubscribe(this.get('thumbnailEventID'));
      this.get('playerRegistry').removeEmbedPlayer(this.elementId);
    } else {
      this._unsubscribeFromAutoplay();
    }
  },

  _subscribeToAutoplay() {
    let enableAutoplay = this.get('enableAutoplay');
    let twitchType = this.get('embed.twitch_type');
    if (enableAutoplay && twitchType) {
      this.get('scrollActivity').subscribe(`${this.elementId}.autoplay`, $('.js-main-col-scroll-content'), () => {
        if (this._embedInFullView() && this.get('thumbnailMode')) {
          this.send('switchToEmbed');
          this._unsubscribeFromAutoplay();
        }
      });
    }
  },

  _unsubscribeFromAutoplay() {
    let enableAutoplay = this.get('enableAutoplay');
    let twitchType = this.get('embed.twitch_type');
    if (enableAutoplay && twitchType) {
      this.get('scrollActivity').unsubscribe(`${this.elementId}.autoplay`);
    }
  },

  _embedInFullView() {
    let embedCoordinates = this._getElBounds();
    return embedCoordinates.bottom < window.innerHeight && embedCoordinates.top > 0;
  },

  _embedOffScreen() {
    let embedCoordinates = this._getElBounds();
    return embedCoordinates.top - window.innerHeight > SWITCH_TO_THUMBNAIL_OFFSET || embedCoordinates.bottom < -SWITCH_TO_THUMBNAIL_OFFSET;
  },

  _switchToThumbnailMode() {
    this.set('thumbnailMode', true);
    this.get('scrollActivity').unsubscribe(this.get('thumbnailEventID'));
    this._subscribeToAutoplay();
    if (this.get('embed.type') === 'video') {
      this.get('playerRegistry').removeEmbedPlayer(this.elementId);
    }
  },

  _getElBounds() {
    let embed = this.get('embedEl');
    return embed.getBoundingClientRect();
  },

  actions: {
    switchToEmbed() {
      this.set('thumbnailMode', false);
      this.get('scrollActivity').subscribe(this.get('thumbnailEventID'), $('.js-main-col-scroll-content'), () => {
        if (this._embedOffScreen()) {
          this._switchToThumbnailMode();
        }
      });
      if (this.get('embed.type') === 'video') {
        this.get('playerRegistry').addEmbedPlayer(this.elementId);
      }
    }
  }
});
