import Component from 'ember-component';
import injectService from 'ember-service/inject';
import nonce from 'web-client/utilities/nonce';
import $ from 'jquery';

export default Component.extend({
  messageToSend: '',
  thread: null,
  tracking: injectService(),
  conversations: injectService("twitch-conversations/conversations"),
  // Default the tab index to 2 because the primary chat input is 1. This value
  // will likely be overridden everywhere this component is used, but let's not
  // default to stepping on toes.
  tabIndex: 2,
  showEmoticonSelector: false,

  init() {
    this._super(...arguments);
    this.emoticonSelectorOutsideClickHandler = this.emoticonSelectorOutsideClickHandler.bind(this);
    $(document).on('click', this.emoticonSelectorOutsideClickHandler);
  },

  willDestroy() {
    this._super(...arguments);
    $(document).off('click', this.emoticonSelectorOutsideClickHandler);
  },

  emoticonSelectorOutsideClickHandler(e) {
    // Auto dismiss the emoticon selector upon a click anywhere else except the icon
    // This method is bound to `this` in init()
    let $selector = this.$('.emoticon-selector-container'),
        $toggle = this.$('.emoticon-selector-toggle');

    if (!$selector.is(e.target) &&
    $selector.has(e.target).length === 0 &&
    !$toggle.is(e.target) &&
    $toggle.has(e.target).length === 0) {
      this.set('showEmoticonSelector', false);
    }
  },

  actions: {
    sendMessage() {
      if (this.get('messageToSend') !== '') {
        // Add the `nonce()` to track whisper reliability
        this.get('conversations').sendMessage(this.get('thread'), this.get('messageToSend'), nonce());
        this.sendAction('scrollToBottom');
        this.set('messageToSend', '');
        this.sendAction('removeDivider');
      }
    },

    toggleEmoticonSelector() {
      this.toggleProperty('showEmoticonSelector');
    },

    selectEmoticon(emoticonRegex) {
      let message = this.get('messageToSend');
      if (message.slice(-1) !== ' ' && message !== '') {
        emoticonRegex = ` ${emoticonRegex}`;
      }
      this.set('messageToSend', `${message}${emoticonRegex} `);
    },

    track(event, data) {
      this.get('tracking').trackEvent({event, data});
    }
  }

});
