import computed from 'ember-computed';
import Component from 'ember-component';
import injectService from 'ember-service/inject';
import ClickOutsideMixin from 'web-client/mixins/click-outside';

export default Component.extend(ClickOutsideMixin, {

  api: injectService(),
  session: injectService(),
  tracking: injectService(),
  premiumGeo: injectService(),
  tagName: 'span',

  creditBalance: null,
  channelName: null,
  isSubscribing: false,

  isMenuOpen: false,

  init() {
    this._super(...arguments);
    this.set('creditBalance', { hasSubCredit: false });
    this._loadBalance();
  },

  clickedOutside() {

    // clicking the subscribe button counts as clicking outside
    if (this.get('isSubscribing')) {
      return;
    }

    if(this.get('isMenuOpen')){
      this.get('trackSubscribeButtonAction')('close_subscribe_menu', this);
    }

    this.set('isMenuOpen', false);
  },

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

  actions: {
    toggle() {
      if(this.get('isMenuOpen')){
        this.get('trackSubscribeButtonAction')('close_subscribe_menu', this);
      } else {
        this.get('trackSubscribeButtonAction')('open_subscribe_menu', this);
      }
      this.toggleProperty('isMenuOpen');
    },
    setIsSubscribing(isSubscribing) {
      this.set('isSubscribing', isSubscribing);
    }
  },

  // eventually balance and prime status should be on the user object
  _loadBalance() {
    let { userData } = this.get('session');
    let token = userData.chat_oauth_token;

    // IE11 caches ajax requests in the browser so we need to bust the cache
    let cacheBuster = Date.now();
    let params = { oauth_token: token, cacheBuster };
    let promise = this.get('api').request('get', '/kraken/user/subscriptions/credit', params);

    promise.then(data => {
      if (this.isDestroyed) { return; }

      let hasSubCredit = data.balance > 0;
      this.set('creditBalance.hasSubCredit', hasSubCredit);
    }, error => {
      if (this.isDestroyed) { return; }

      if (error.status && error.status >= 400) {
        this.set('creditBalance.hasSubCredit', false);
        return;
      }
    });
  }
});
