import Component from 'ember-component';
import computed from 'ember-computed';
import injectService from 'ember-service/inject';
import on from 'ember-evented/on';
import run from 'ember-runloop';
import { libraries as libs } from 'web-client/utilities/conversations-util';
import { KEY_CODES } from 'web-client/utilities/keyboard';
import { formatDisplayName } from 'web-client/helpers/format-display-name';

export default Component.extend({
  classNames: ['conversations-list-item'],
  classNameBindings: ['hasFocus:has-focus'],
  conversation: {},
  conversations: injectService("twitch-conversations/conversations"),
  session: injectService(),
  api: injectService(),
  tracking: injectService(),
  thread: computed.alias('conversation.thread'),
  hasFocus: false,

  conversationLogo: libs.defaultAvatar,

  conversationName: computed('thread.participants', function () {
    let otherUser = this.get('thread.participants').rejectBy('id', this.get('session.userData.id').toString()).objectAt(0);
    if (otherUser.get('displayName')) {
      return formatDisplayName(otherUser.get('username'), otherUser.get('displayName'));
    }
    return otherUser.get('username');
  }),

  _setConversationLogo: on('init', function () {
    let otherUser = this.get('thread.participants').rejectBy('id', this.get('session.userData.id').toString()).objectAt(0);
    this.get('api').request('get', `users/${otherUser.get('username')}`).then(otherUserData => {
      if (!this.isDestroyed && otherUserData.logo) {
        this.set('conversationLogo', otherUserData.logo);
      }
    });
  }),

  conversationUnreadCount: computed.alias('thread.unreadCount'),

  didReceiveAttrs() {
    this._super(...arguments);
    this._grabFocus();
  },

  _grabFocus() {
    let hasFocus = this.get('hasFocus');
    if (hasFocus && !this.lastFocus) {
      run.schedule('afterRender', () => {
        if (this.$().is(':visible')) {
          this.$().children('.conversation-container').focus();
        }
      });
    }
    this.lastFocus = hasFocus;
  },

  keyUp(e) {
    return this._handleKeyEvent(e);
  },

  _handleKeyEvent(e) {
    let key = e.keyCode;
    if (key === KEY_CODES.enter || key === KEY_CODES.space) {
      this.send('makeActive');
      e.preventDefault();
    }
  },

  actions: {
    makeActive() {
      this.get('conversations').makeActive(this.get('conversation'));
      this.get('conversations').display(this.get('conversation'));
      this.get('conversations').maximize(this.get('conversation'));
      this.set('conversation.isFocused', true);
      let onSearchResultClicked = this.get('onSearchResultClicked');
      if (typeof onSearchResultClicked === 'function') {
        onSearchResultClicked({
          rank: this.get('rank'),
          isConversation: true
        });
      }
      this.sendAction('hideList');
    },

    archive() {
      this.get('conversations').archive(this.get('conversation'));

      let event = 'chat_convo_mod';
      let data = {
        conversation_id: this.get('thread.id'),
        action: 'archive',
        login: this.get('session.userData.login')
      };
      this.get('tracking').trackEvent({event, data});
    }
  }

});
