/* globals Twitch */

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

export default Component.extend(ClickOutsideMixin, {

  api: injectService(),
  session: injectService(),
  tagName: "span",

  hasSubCredit: null,
  channelName: null,
  campaign: null,
  shouldRenderUseCredit: false,
  isSubscribing: false,
  hasPrime: false,

  urlParams,

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

    let { isAuthenticated, userData } = this.get('session');
    if (isAuthenticated) {
      this.set('hasPrime', userData.has_premium);
      if (this.get('hasPrime')) {
        this._loadBalance(userData);
      }
    }

    this._handleWelcomeAction();
  },

  href: computed('channel.id', 'campaign', function () {
    return Twitch.uri.subscribe(this.get('channel.id'), this.get('campaign'));
  }),

  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(userData) {
    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('hasSubCredit', hasSubCredit);
    }, error => {
      if (this.isDestroyed) { return; }

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

  _handleWelcomeAction() {
    if (this.get('urlParams').expandsubmodal) {
      this.set('isMenuOpen', true);
    }
  }
});
