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

export default Component.extend(SendRouteActionMixin, {
  store: injectService(),
  presence: injectService('twitch-presence/presence'),

  user: null,
  userId: null,

  didReceiveAttrs() {
    this._super(...arguments);
    let user = this.get('store').peekRecord('friends-list-user', this.get('userId'));
    if (user) {
      this.set('user', user);
    }
  },

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

    return hasAtLeastOneActivity;
  }),

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

  presenceString: computed('activity', function() {
    return getActivityString(this.get('activity'));
  }),

  truncatedPresence: computed('presenceString', function() {
    return getActivityString(this.get('activity'), true);
  }),

  location: computed('activity', 'hasActivity', 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: {
    clickPresence(event) {
      this.get('presence').trackClickPresence(this.get('user.login'), this.get('location'), this.get('activity'), 'conversations');
      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 });
      }
    }
  }

});
