/* globals i18n */
import computed from 'ember-computed';
import injectService from 'ember-service/inject';
import Component from 'ember-component';
import { isPresent } from 'ember-utils';
import { getRichPresence } from 'web-client/utilities/presence-util';

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

  onClick: null,
  isOnline: null,

  isLoaded: computed('isOnline', 'presence.areSettingsLoaded', function () {
    return isPresent(this.get('isOnline')) || this.get('presence.areSettingsLoaded');
  }),

  isOnlineManuallySet: computed('isOnline', function () {
    return isPresent(this.get('isOnline'));
  }),

  /**
   * Alias for `isOnline` if provided, otherwise fallback to the friends service for live updates
   */
  //TODO use friends.self.availability as the dependent key
  online: computed('isOnline', 'friends.self', function () {
    let isOnline = this.get('isOnline');
    let selfObj = this.get('friends.self');
    if (isPresent(isOnline)) {
      return isOnline;
    }

    if (selfObj && selfObj.get('availability') === 'online') {
      return true;
    }

    return false;
  }),

  //TODO use friends.self.availability as the dependent key
  idle: computed('friends.self', function () {
    let selfObj = this.get('friends.self');
    if (selfObj && selfObj.get('availability') === 'idle') {
      return true;
    }
    return false;
  }),

  statusIndicatorClass: computed('isOnline', 'online', 'idle', 'presence.settings.share_activity', function(){
    let klass = 'presence--online';

    if ((this.get('isOnlineManuallySet') && !this.get('isOnline')) || (!this.get('online') && !this.get('idle'))) {
      klass = 'presence--invisible';
    } else if (!this.get('isOnlineManuallySet') && this.get('idle')) {
      klass = 'presence--idle';
    } else if ((this.get('isOnlineManuallySet') && this.get('isOnline')) || !this.get('presence.settings.share_activity')) {
      klass = 'presence--online';
    }

    return klass;
  }),

  statusString: computed('isOnlineManuallySet', 'isOnline', 'online', 'idle', 'presence.settings.share_activity', 'friends.self', function() {
    if ((this.get('isOnlineManuallySet') && !this.get('isOnline')) || (!this.get('online') && !this.get('idle'))) {
      return i18n('Invisible');
    }

    if ((this.get('isOnlineManuallySet') && this.get('isOnline')) || !this.get('presence.settings.share_activity')) {
      return i18n('Online');
    }

    let selfObj = this.get('friends.self');

    if (selfObj) {
      let selfActivities = this.get('friends.self.activities');

      if (!selfActivities) { return ''; }

      return getRichPresence(selfObj.get('availability'), selfActivities[0]);
    }
  }),

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