import Component from 'ember-component';
import injectService from 'ember-service/inject';
import run from 'ember-runloop';
import { keyboardListener } from 'web-client/utilities/keyboard';
import computed from 'ember-computed';

const ClipsModalPlayback = Component.extend({
  classNames: ['card'],
  persistentPlayer: injectService(),
  activeClipIndex: null,
  leftArrowIsVisible: computed.bool('activeClipIndex'),
  arrowsAreVisible: computed('clips', function() {
    const clips = this.get('clips');
    return clips && clips.items.length > 1;
  }),

  clips: null,

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

  didInsertElement() {
    let playerComponent = this.get('persistentPlayer.playerComponent');

    if (playerComponent) {
      playerComponent.pause();
    }

    this.addEventListener(...keyboardListener({
      left: this.get('actions').onPrevClipClick,
      right: this.get('actions').onNextClipClick
    }));
  },

  actions: {
    selectShareURL() {
      // https://bugs.webkit.org/show_bug.cgi?id=22691
      run.next(() => {
        this.$('#share-url-copy').select();
      });
    },
    openRemoveModal() {
      this.get('openRemoveModal')();
    },
    openReportModal() {
      this.get('openReportModal')();
    },
    onPrevClipClick() {
      const activeClipIndex = this.get('activeClipIndex');
      const previousClipIndex = activeClipIndex - 1;
      const previousClip = this.get('clips').items[previousClipIndex];

      if (previousClip) {
        this.get('openPlaybackModal')(previousClip, previousClipIndex);
      }
    },
    onNextClipClick() {
      const clips = this.get('clips');

      let activeClipIndex = this.get('activeClipIndex');
      let nextClipIndex = activeClipIndex + 1;
      let nextClip = clips.items[nextClipIndex];

      if (nextClip) {
        this.get('openPlaybackModal')(nextClip, nextClipIndex);
      } else if (!clips.items.isLoading) {
        clips.fetchNextPage().then(() => {
          nextClip = clips.items[nextClipIndex];

          if (!nextClip) {
            nextClipIndex = 0;
            nextClip = clips.items[nextClipIndex];
          }

          this.get('openPlaybackModal')(nextClip, nextClipIndex);
        });
      }
    }
  }
});

ClipsModalPlayback.reopenClass({
  positionalParams: ['clip']
});

export default ClipsModalPlayback;
