import run from 'ember-runloop';
import computed from 'ember-computed';
import Component from 'ember-component';
import injectService from 'ember-service/inject';
import InteractivityDeferredComponent from 'web-client/mixins/interactivity-deferred-component';

export default Component.extend(InteractivityDeferredComponent, {
  session: injectService(),
  vodGameInfo: injectService(),
  vodCoviews: injectService(),
  vodResumeWatching: injectService(),
  cachedExperiments: injectService(),

  isButtonVisible: false,
  isMenuVisible: false,
  showTags: false,
  animatePreview: computed.and('previewLoaded', 'isHovering'),
  isAdmin: computed.or('session.userData.is_admin', 'session.userData.is_staff'),
  vodResumeWatchingIsEnabled: computed.alias('vodResumeWatching.isEnabled'),

  preview: computed('video.preview', function() {
    // v4 API which we use for similar videos returns a hash.
    let preview = this.get('video.preview');
    if (typeof preview === 'string') {
      return preview;
    }

    return preview.medium;
  }),

  init() {
    this._super(...arguments);
    this.set('experimentEnabled', false);
    this.get('cachedExperiments').getExperimentPromise('SNAIL').then(value => {
      this.set('experimentEnabled', value !== 'control');
    });
  },

  didInsertElement() {
    this._super(...arguments);
    this.addEventListener(this.element, 'mouseenter', () => {
      this.set('isButtonVisible', true);
      this.set('isHovering', true);

      if (this.get('previewLoaded') || this.get('video.animated_preview_url') === undefined) {
        return;
      }

      if (this.get('experimentEnabled')) {
        let img = new Image();
        img.onload = () => {
          if (this.isDestroyed) {
            return;
          }
          run(() => {
            this.set('previewLoaded', true);
          });
        };
        img.src = this.get('video.animated_preview_url');
      }
    });
    this.addEventListener(this.element, 'mouseleave', () => {
      this.set('isButtonVisible', false);
      this.set('isMenuVisible', false);
      this.set('isHovering', false);
    });

    run.scheduleOnce('afterRender', this, this.reportInteractive);
  },

  actions: {
    toggleMenuVisibility() {
      let visibility = !this.get('isMenuVisible');
      this.set('isMenuVisible', visibility);
    }
  }
});
