import computed from 'ember-computed';
import run from 'ember-runloop';
import injectService from 'ember-service/inject';
import VideoPreviewCard from 'web-client/components/video/preview-card/component';

export default VideoPreviewCard.extend({
  vodCoviews: injectService(),
  cachedExperiments: injectService(),

  showBoxart: true,
  isMenuVisible: false,
  isButtonVisible: false,

  video: computed.alias('content'),
  totalVideos: computed.alias('totalItems'),

  animatePreview: computed.and('previewLoaded', 'isHovering'),

  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');
    });
  },

  mouseEnter() {
    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');
    }
  },

  mouseLeave() {
    this.set('isHovering', false);
  },

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