import computed from 'ember-computed';
import Component from 'ember-component';
import injectService from 'ember-service/inject';
import { scheduleOnce } from 'ember-runloop';
import VodCoviewsTrackingMixin from 'web-client/mixins/vod-coviews/tracking';
import InteractivityDeferredComponent from 'web-client/mixins/interactivity-deferred-component';

/*
  This component is a base for a new component on the redesigned following directory.
  Please make sure that changes you make here do not impact that subcomponent as well:
    /app/templates/components/newsfeed-redesign/vod-coview.hbs
*/
export default Component.extend(VodCoviewsTrackingMixin, InteractivityDeferredComponent, {
  vodCoviews: injectService(),
  browse: injectService(),

  // props passed
  largeHeader: null,
  tt_medium: null,
  tt_content: null,
  maxVodsPerRow: 0,

  isBrowseExperimentEnabled: computed.readOnly('browse.isBrowseExperimentEnabled'),

  recommendedVods: computed.alias('vodCoviews.recommendedVods'),

  vodToRemove: null,
  vodIndexToRemove: null,

  areVodsViewable: computed.alias('vodCoviews.areVodsViewable'),

  numRecsViewable: computed('recommendedVods', 'maxVodsPerRow', function () {
    return Math.min(this.get('recommendedVods').length, this.get('maxVodsPerRow'));
  }),

  didInsertElement() {
    this._super(...arguments);

    this.trackCoviewRecommendation();

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

  recommendedVodsToShow: computed('maxVodsPerRow', 'recommendedVods.[]', function () {
    let vods = this.get('recommendedVods');

    return vods.slice(0, this.get('maxVodsPerRow'));
  }),

  isLoading: computed.alias('content.isLoading'),

  actions: {
    undoDismissClick(vod, position) {
      this.get('vodCoviews').undoDismissRecommendation(vod.id, position);
      this.rerender();

      this.trackUndo(vod, position);
    },

    openInModal(video, position) {
      this.set('vodToRemove', video);
      this.set('vodIndexToRemove', position);
      this.sendAction('openInModal', 'components/vod-coview-dismiss-modal', this);
    },

    closeModal() {
      this.set('vodToRemove', null);
      this.set('vodIndexToRemove', null);
      this.sendAction('closeModal', this);
    },

    submitFeedback(text, reason, vod, position) {
      this.set('vodToRemove', null);
      this.set('vodIndexToRemove', null);

      this.get('recommendedVods')[position].removed = true;
      this.sendAction('closeModal', this);
      this.rerender();

      this.trackSubmitFeedback(vod, position, reason, text);
    },

    handleDismissClick(vod, position) {
      this.get('vodCoviews').dismissRecommendation(vod.id);
      this.rerender();

      this.trackDismiss(vod, position);
    }
  }
});
