import injectService from 'ember-service/inject';
import computed from 'ember-computed';
import Component from 'ember-component';
import { getRichPresence } from 'web-client/utilities/presence-util';
import SendRouteActionMixin from 'web-client/mixins/send-route-action';
import { libraries as libs } from 'web-client/utilities/conversations-util';

export default Component.extend(SendRouteActionMixin, {
  classNames: ['js-friend-info'],

  presence: injectService('twitch-presence/presence'),
  friends: injectService('twitch-friends-list/friends'),
  session: injectService(),
  store: injectService(),
  api: injectService(),
  conversations: injectService('twitch-conversations/conversations'),
  tracking: injectService(),

  friend: null,
  login: null,
  displayName: null,
  avatarUrl: libs.defaultAvatar,

  userId: computed('otherUser.id', 'friend.id', function() {
    return this.get('otherUser.id') || this.get('friend.id');
  }),

  userLogin: computed('otherUser.username', 'friend.login', function() {
    return this.get('otherUser.username') || this.get('friend.login');
  }),

  otherUser: computed('thread.participants', function () {
    if (!this.get('thread')) {
      return null;
    }
    return this.get('thread.participants').rejectBy('id', this.get('session.userData.id').toString()).objectAt(0);
  }),

  thread: computed.alias('conversation.thread'),

  friendThread: computed('conversations.isLoading', 'userId', 'conversations.sortedConversations', function() {
    if (!this.get('conversation') && !this.get('conversations.isLoading') && this.get('userId')) {
      let friendId = this.get('userId');
      let selfId = this.get('session.userData.id');
      let threadAttempt = this.get('store').peekRecord('thread', `${friendId}_${selfId}`);
      let threadRevAttempt = this.get('store').peekRecord('thread', `${selfId}_${friendId}`);
      return threadAttempt || threadRevAttempt;
    }
  }),

  unreadCount: computed('thread.unreadCount', 'friendThread.unreadCount', function() {
    if (this.get('thread')) {
      return this.get('thread.unreadCount');
    }
    if (this.get('friendThread')) {
      return this.get('friendThread.unreadCount');
    }
  }),

  init() {
    this._super(...arguments);
    if (this.get('thread')) {
      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('avatarUrl', otherUserData.logo);
        }
      });

      this.set('login', this.get('otherUser.username'));
      this.set('displayName', this.get('otherUser.displayName'));
    }
  },

  statusString: computed('friend.isOnline', 'activity', 'friend.isIdle', function () {
    return getRichPresence(this.get('friend.availability'), this.get('activity'));
  }),

  hasActivity: computed('friend.activities', function() {
    return this.get('friend.activities') && this.get('friend.activities').length > 0 && this.get('friend.activities')[0].type !== 'none';
  }),

  activity: computed('hasActivity', 'friend.activities.@each', function() {
    if (this.get('hasActivity')) {
      return this.get('friend.activities')[0];
    }
    return null;
  }),

  friendLocation: computed('friend.login', 'hasActivity', 'activity', function () {
    if (this.get('hasActivity')) {
      if (this.get('activity.channel_login')) {
        return this.get('activity.channel_login');
      } else if (['broadcasting', 'streaming'].includes(this.get('activity').type)) {
        return this.get('friend.login');
      }
    }
  }),

  actions: {
    archive() {
      this.get('conversations').archive(this.get('conversation'));
      if (this.get('conversations.activeConversation') === this.get('conversation')) {
        this.sendAction('closeConversation');
      }

      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});
    }
  }

});
