/* globals i18n */

import Ember from 'ember';
import computed from 'ember-computed';
import injectService from 'ember-service/inject';
import cdnUrl from 'web-client/utilities/cdn-url';
import config from 'web-client/config/environment';
import Component from 'ember-tether/components/ember-tether';
import {
  CONTENT_CODE_URL as landingHref,
  CONTENT_CODE_LINK_URL as linkingHref
} from 'web-client/utilities/urls/prime-urls';
import {
  COPY_OFFER_CODE_KEY as copyOfferCodeKey
} from 'web-client/utilities/samus/prime-tracking-keys';


const { Logger } = Ember;

export default Component.extend({
  api: injectService(),
  session: injectService(),
  storage: injectService(),
  claimOffer: injectService(),
  tracking: injectService(),
  classNames: ['offer-item__balloon', 'balloon', 'balloon--right'],
  code: null,
  target: computed.readOnly('tetherId'),
  targetAttachment: 'top right',
  attachment: 'top left',
  offset: '170px 0',
  offer: null,
  hasCode: computed.bool('code'),
  isCopied: false,
  isClaimingOffer: false,
  errorMessage: null,
  stayOpen: false,
  hasClaimedOffer: false,

  claimInstruction: null,
  offerClaimInstruction: computed.readOnly('offer.contentClaimInstruction'),
  contentClaimInstruction: computed.or('claimInstruction', 'offerClaimInstruction'),

  landingHref: computed('landingHref', 'window.location.pathname', function() {
    let redirectRoute = btoa(window.location.pathname.substring(1));
    return `${landingHref}&redirectRoute=${redirectRoute}`;
  }),

  linkingHref: computed('linkingHref', 'window.location.pathname', function() {
    let redirectRoute = btoa(window.location.pathname.substring(1));
    return `${linkingHref}&redirectRoute=${redirectRoute}`;
  }),

  spinnerImage: computed(function () {
    return cdnUrl('images/spinner.gif');
  }),

  buttonText: computed('offer.contentDeliveryMethod', function () {
    if (this.get('offer.contentDeliveryMethod') === 'DIRECT_ENTITLEMENT') {
      return i18n('Claim Offer');
    }

    return i18n('Get Code');
  }),

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

    let claimCode = this.get('claimOffer.offerIdToCode')[this.get('offer.id')];

    let offerId = this.get('offer.id');
    let tuid = this.get('session.userData.id');
    let claimedOfferId = `${offerId}-${tuid}`;

    if (claimCode === 'DIRECT_ENTITLEMENT') {
      this.set('hasClaimedOffer', true);
    } else if (claimCode) {
      this.set('code', claimCode);
    } else if (this.get('claimedOfferIds') && this.get('claimedOfferIds').includes(claimedOfferId)) {
      this.send('claimOffer');
    }
  },

  mouseEnter() {
    this.set('stayOpen', true);
    this.set('parentView.childHover', true);
  },

  mouseLeave() {
    if (this.get('isClaimingOffer')) { return; }

    let timeout = config.delay.premium.flyout;

    this.set('stayOpen', false);
    this.runTask(() => {
      if (!this.get('stayOpen')) {
        this.set('parentView.childHover', false);
      }
    }, timeout);
  },

  actions: {
    claimOffer(){
      if (this.get('isClaimingOffer')) { return; }
      this.set('isClaimingOffer', true);
      this.set('stayOpen', true);

      let offerId = this.get('offer.id');

      this.get('claimOffer').claim(offerId)
        .then(data => {
          if (this.isDestroyed) { return; }

          let tuid = this.get('session.userData.id');
          let claimedOfferId = `${offerId}-${tuid}`;

          let currentlyClaimedStorage = this.get('storage.claimedOfferIds') || '[]';
          let currentlyClaimed = JSON.parse(currentlyClaimedStorage);
          let newlyClaimed = currentlyClaimed.concat(claimedOfferId);
          this.set('storage.claimedOfferIds', JSON.stringify(newlyClaimed));
          this.set('claimedOfferIds', newlyClaimed);
          this.set('claimInstruction', data.contentClaimInstruction);

          if(data.type === 'DIRECT_ENTITLEMENT') {
            this.set('hasClaimedOffer', true);
            this.set(`claimOffer.offerIdToCode.${offerId}`, data.type);

            return;
          }

          this.set('code', data.claimData);
          this.set(`claimOffer.offerIdToCode.${offerId}`, data.claimData);
        })
        .finally(() => {
          if (this.isDestroyed) { return; }

          let timeout = config.delay.premium.getCode;
          this.runTask(() => {
            this.set('isClaimingOffer', false);
          }, timeout);
        });
    },

    success(){
      this.set('isCopied', true);

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

      this.get('tracking').trackEvent({
        event: copyOfferCodeKey,
        data: {
          time: Date.now(),
          offerId: this.get('offer.id'),
          userData: userData
        }
      });
      this.runTask(() => {
        this.set('isCopied', false);
      }, 1000);
    },

    error(){
      Logger.error("Error copying to clipboard");
    }
  }
});
