/* 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 {
  getFaqUrl
} from 'web-client/utilities/urls/prime-urls';

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

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

  resubscribeHeaderText: computed('channel.displayName', function () {
    let subscribeToTextTemplate = i18n('Resubscribe to {{channel}}');
    return subscribeToTextTemplate.replace('{{channel}}', this.get('channel.displayName'));
  }),

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

  canSubscribe: computed('creditBalance.hasSubCredit', function() {
    return this.get('creditBalance.hasSubCredit');
  }),

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

  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')();
          this.set('creditBalance.hasSubCredit', false);
          this.set('channel.isSubscribed.isSubscribed', true);
        })
        .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);
        });

    }
  }
});
