/* globals i18n */

import computed from 'ember-computed';
import Component from 'ember-tether/components/ember-tether';
import injectService from 'ember-service/inject';
import cdnUrl from 'web-client/utilities/cdn-url';
import {
  SUB_BUTTON_URL as primeSubTrialHref,
  SUB_BUTTON_LINK_URL as primeSubLinkHref,
  getFaqUrl
} from 'web-client/utilities/urls/prime-urls';

export default Component.extend({
  classNames: ['subscription-modal__balloon', 'subscription-modal__balloon--subscribe', 'balloon', 'balloon--no-padding'],
  subscriptionCredit: injectService(),
  notify: injectService(),

  channel: undefined,

  //ember-tether properties
  target: computed.readOnly('tetherId'),
  attachment: 'bottom left', // to where sub button modal is connected to the button
  targetAttachment: 'top left',  // from where on the button the sub modal will be displayed
  offset: '0 0', // offset Y and X

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

  click(event) {
    event.stopPropagation();
  },

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

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

  faqUrl: computed('', function() {
    return getFaqUrl();
  }),

  actions: {
    close() {
      this.get('trackSubscribeButtonAction')('close_subscribe_menu', this);
      this.get('toggle')();
    },

    trackLinkClick(linkActionName){
      this.get('trackSubscribeButtonAction')(linkActionName, this);
    },

    samusSpendCredit(channel) {
      this.get('trackSubscribeButtonAction')('samus_spend_credit', this);
      this.get('setIsSubscribing')(true);

      //start spinner
      this.set('shouldRenderUseCredit', false);

      this.get('subscriptionCredit').spendCredit(channel)
        .then(() => {
          if (this.isDestroyed) { return; }

          this.get('toggle')();
          this.get('toggleHasSubscribedMessage')();

          // acts like a samus ticket
          channel.set('isSubscribed.isSubscribed', true);
          channel.set('isSubscribed.content', [{
            product: {period: 'Month'},
            purchase_profile: {payment_provider: 'samus'}
          }]);
        })
        .catch(error => {
          if (this.isDestroyed) { return; }

          if (error.status && error.status >= 400) {
            this.get('notify').error(i18n('Sorry, there was a problem spending your Prime credit.'));
            return;
          }
          throw error;
        })
        .finally(() => {
          if (this.isDestroyed) { return; }

          this.get('setIsSubscribing')(false);
        });

    }
  }
});
