import Service from 'ember-service';
import computed from 'ember-computed';

export default Service.extend({
  mainPlayer: computed('players.[]', function() {
    let players = this.get('players');
    return players.get('firstObject');
  }),

  init () {
    this._super(...arguments);
    this.players = [];
    this.embedPlayers = [];
    // featuredPlayer represents the front page carousel player
    // It is a different player from the players stored in the players array
    this.featuredPlayer = null;
  },
  add (player) {
    // determine if player is ember component object or player-ui embed
    if (player.classNames && player.classNames.indexOf('js-twitch-player-2') > -1) {
      this.players.pushObject(player);
    } else {
      this.featuredPlayer = player;
      if (this.isAnyPlaying()) {
        player.addEventListener('playing', function pausePlayer() {
          player.pause();
          player.removeEventListener('playing', pausePlayer);
        });
      }
    }
  },
  remove (player) {
    this.players.removeObject(player);
  },
  clear () {
    this.players.clear();
  },
  addEmbedPlayer(embedElementID) {
    let mainPlayer = this.get('mainPlayer');
    let featuredPlayer = this.get('featuredPlayer');
    this.embedPlayers.pushObject(embedElementID);
    if (mainPlayer && mainPlayer.get('player').isPlaying()) {
      mainPlayer.get('player').pause();
    }
    if (featuredPlayer && !featuredPlayer.isPaused()) {
      featuredPlayer.pause();
    }
  },
  removeEmbedPlayer(embedElementID) {
    let mainPlayer = this.get('mainPlayer');
    this.embedPlayers.removeObject(embedElementID);
    if (mainPlayer && this.embedPlayers.length === 0 && !mainPlayer.get('userSetPlayerToPause')) {
      mainPlayer.get('player').play();
    }
  },
  isAnyPlaying () {
    return this.players.some(({player}) => {
      if (!player || typeof player.isPlaying !== 'function') {
        return false;
      }
      return player.isPlaying();
    });
  }
});
