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

import { KEY_CODES } from 'web-client/utilities/keyboard';

export default Component.extend({
  classNames: ['js-conversations-search-user', 'conversations-list-item'],
  classNameBindings: ['hasFocus:has-focus'],
  user: null,
  conversations: injectService("twitch-conversations/conversations"),
  session: injectService(),
  tracking: injectService(),
  hasFocus: false,
  attributeBindings: ['tabindex'],
  tabindex: -1,

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

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

  avatarUrl: computed('user.logo', function () {
    return this.get('user.logo') || libs.defaultAvatar;
  }),

  userDisplayName: computed('user.display_name', 'user.name', function() {
    if (this.get('user.display_name')) {
      return formatDisplayName(this.get('user.name'), this.get('user.display_name'));
    }
    return this.get('user.name');
  }),

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

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

  click() {
    this.send('createConversation');
  },

  actions: {
    createConversation() {
      let userName = this.get('user.name');
      let rank = this.get('rank');
      let conversations = this.get('conversations');
      let onSearchResultClicked = this.get('onSearchResultClicked');
      let startConversationPromise = conversations.startConversationForUsername(userName);

      startConversationPromise.then(conversation => {
        let event = 'chat_convo_create';
        let data = {
          conversation_id: conversation.get('thread.id'),
          login: this.get('session.userData.login'),
          target_login: userName,
          source: 'search_target_result',
          search_result_rank: rank
        };
        this.get('tracking').trackEvent({event, data});
      });

      if (typeof onSearchResultClicked === 'function') {
        onSearchResultClicked({
          rank: rank,
          isConversation: false
        });
      }

      this.sendAction('hideList');
    }
  }
});
