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 { getNonStrangerReason } from 'web-client/utilities/friends-list/reasons';

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

  presence: injectService('twitch-presence/presence'),

  user: null,

  shouldShowPresence: computed('user', 'uiContext', function () {
    return this.get('user.isFriend') && this.get('uiContext') === 'friendList';
  }),

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

  nonStrangerString: computed(function() {
    // getNonStrangerReason returns a translated string already
    return getNonStrangerReason(this.get('nonStrangerReason'));
  }),

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

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

  userLocation: computed('user.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('user.login')}`;
      }
    }
  }),

  actions: {
    onClick() {
      let onClick = this.get('onClick');
      if (typeof(onClick) === 'function') {
        onClick(this.get('user'));
      }
    },

    clickPresence(event) {
      this.get('presence').trackClickPresence(this.get('user.login'), this.get('userLocation'), this.get('activity'), 'friends');
      let id;
      if (this.get('activity.channel_login')) {
        id = this.get('activity.channel_login');
      } else if (['broadcasting', 'streaming'].includes(this.get('activity').type)) {
        id = this.get('user.login');
      }

      // Do not send route action if control key, command key, or middle click is used
      if (event && !event.ctrlKey && !event.metaKey && event.button !== 1) {
        this.sendRouteAction('handleStreamClick', { id });
      }
    }
  }
});
