/* global i18n */

import Component from 'ember-component';
import computed from 'ember-computed';
import observer from 'ember-metal/observer';
import run from 'ember-runloop';
import injectService from 'ember-service/inject';
import TicketModel from 'web-client/models/ticket';

export default Component.extend({
  classNames: ['js-chat-interface'],

  tracking: injectService(),
  settings: injectService('chatSettings'),

  hideSettingsMenu: true,

  subscribeToUnlockText: i18n('Subscribe to unlock Emoticons'),

  tickets: null,

  isLoadingSubscription: computed.readOnly('tickets.isLoading'),

  isSubscribed: computed.notEmpty('tickets.content'),

  submitButtonText: computed('room.isWhisperMessage', function () {
    return i18n(this.get('room.isWhisperMessage') ? 'Whisper' : 'Chat');
  }),

  showFollowersNotification: false,

  showEmoticonSelectorToggle: computed('room.product.emoticons', 'allEmoticonImages', function () {
    let hasChannelEmotes = this.get('room.product.emoticons') && this.get('room.product.emoticons').length > 0;
    let hasAllEmotes = Object.keys(this.get('allEmoticonImages')).length > 0;
    return hasChannelEmotes || hasAllEmotes;
  }),

  setAllEmoticonImages: observer('tmiSession', function () {
    let tmiSession = this.get('tmiSession');
    if (!tmiSession) { return; }

    let cachedResponse = tmiSession.getEmotes();
    if (cachedResponse) {
      this.set('allEmoticonImages', cachedResponse);
    }

    if (this._emotesChangedHandler) {
      tmiSession.off('emotes_changed', this._emotesChangedHandler);
    }

    this._emotesChangedHandler = (response) => {
      if (this.isDestroyed) { return; }

      run(() => this.set('allEmoticonImages', response));
    };

    tmiSession.on('emotes_changed', this._emotesChangedHandler);
  }),

  init() {
    this._super(...arguments);
    this.set('allEmoticonImages', {});

    let roomID = this.get('room.id');
    let tickets = TicketModel.find('user', { channel: roomID });

    if (!tickets.get('isLoaded')) {
      tickets.load();
    }

    let hasSeenNotification = this.get('settings.hasSeenFollowersNotification');
    if (!hasSeenNotification) {
      this.set('showFollowersNotification', true);
      this.set('settings.hasSeenFollowersNotification', true);
    }

    this.set('tickets', tickets);
  },

  willDestroyElement() {
    if (this._emotesChangedHandler) {
      this.get('tmiSession').off('emotes_changed', this._emotesChangedHandler);
    }

    this._super(...arguments);
  },

  actions: {
    selectEmoticon(regex) {
      // The subscription check is now done in the selector addon
      let currentMessage = this.get('room.messageToSend');
      if (currentMessage.slice(-1) !== ' ' && currentMessage !== '') {
        regex = ` ${regex}`;
      }
      this.set('room.messageToSend', `${this.get('room.messageToSend')}${regex} `);
      this.get('tracking').trackEvent({
        services: ['mixpanel'],
        event: 'emoticon-selector-click',
        data: { channel: this.get('room.id') }
      });
    },

    setColor(color) {
      this.get('tmiSession').setColor(color);
      this.set('room.chatColor', color);
    },

    toggleSettingsPopup() {
      this.toggleProperty('hideSettingsMenu');
      this.send('dismissFollowersNotification');

      // Track when a user opens the settings menu.
      if (!this.get('hideSettingsMenu')){
        let room = this.get('room');
        if (room) {
          this.get('tracking').trackEvent({
            event: 'chat_client_settings_open',
            data: room.getTrackingData()
          });
        }
      }
    },

    dismissFollowersNotification() {
      this.set('showFollowersNotification', false);
    }
  }
});
