import Component from 'ember-component';
import hoverintent from 'hoverintent';
import computed from 'ember-computed';
import run from 'ember-runloop';
import injectService from 'ember-service/inject';
import {
  HOVER_OFFER_KEY as hoverOfferKey,
  HIDE_OFFER_KEY as hideOfferKey
} from 'web-client/utilities/samus/prime-tracking-keys';


export default Component.extend({
  session: injectService(),
  storage: injectService(),
  tracking: injectService(),
  tagName: 'dd',
  classNames: 'warp__item balloon-wrapper offer-item',
  childHover: false,
  tooltip: false,
  showAllOffers: null,
  hoverListener: null,
  offerClaimed: computed('claimedOfferIds', function() {
    let offerId = this.get('offer.id');
    let tuid = this.get('session.userData.id');
    let claimedOfferId = `${offerId}-${tuid}`;
    return this.get('claimedOfferIds') && this.get('claimedOfferIds').includes(claimedOfferId);
  }),

  showTooltip: computed.or('tooltip', 'childHover'),

  // prevent the link in the offer item title being followed
  click(e) {
    e.preventDefault();
  },

  didInsertElement() {
    this._super(...arguments);
    this.hoverListener = hoverintent(this.$()[0], () => {
      run(() => {
        let { userData } = this.get('session');

        this.get('tracking').trackEvent({
          event: hoverOfferKey,
          data: {
            time: Date.now(),
            offerId: this.get('offer.id'),
            userData: userData
          }
        });
        this.set('tooltip', true);
      });
    }, () => {
      this.runTask(() => {
        this.set('tooltip', false);
      }, 100);
    });
  },

  tetherId: computed('elementId', function(){
    return `#${this.get('elementId')}`;
  }),

  willDestroyElement() {
    this.hoverListener.remove();
    this._super(...arguments);
  },

  actions: {
    hideOffer() {
      let tuid = this.get('session.userData.id');
      let offerId = this.get('offer.id');

      let currentlyHiddenStorage = this.get('storage.hiddenOfferIds') || '[]';
      let currentlyHidden = JSON.parse(currentlyHiddenStorage);
      let newlyHidden = null;

      if (tuid) {
        newlyHidden = currentlyHidden.concat(`${offerId}-${tuid}`);
      } else {
        newlyHidden = currentlyHidden.concat(offerId);
      }

      this.set('storage.hiddenOfferIds', JSON.stringify(newlyHidden));
      this.set('hiddenOfferIds', newlyHidden);

      let { userData } = this.get('session');

      this.get('tracking').trackEvent({
        event: hideOfferKey,
        data: {
          time: Date.now(),
          offerId: offerId,
          userData: userData
        }
      });
    }
  }
});
