import Component from 'ember-component';
import injectService from 'ember-service/inject';
import run from 'ember-runloop';

export default Component.extend({
  communities: injectService(),
  search: injectService('twitch-friends-list/search'),
  session: injectService(),
  store: injectService(),
  tracking: injectService(),

  query: null,
  searchResults: null,
  hasError: false,
  moderators: [],
  isLoading: false,
  isLoadingMods: false,

  init() {
    this._super(...arguments);
    this.set('isLoadingMods', true);
    this.get('communities').fetchModerators().then(data => {
      if (this.isDestroyed) { return; }
      this.set('moderators', data.moderators);
      this.set('isLoadingMods', false);
    });
  },

  _search(query) {
    if (this.isDestroyed) { return; }
    this.get('search').searchNoRelationship(query).then(results => {
      if (this.isDestroyed) { return; }
      if (this.get('query').trim().toLowerCase() !== query) {
        //
        // If the query changed while we were fetching results, throw
        // away the results.
        //
        return;
      }
      results = results.map(user => {
        return {
          _id: user.get('id'),
          name: user.get('login'),
          display_name: user.get('displayName'),
          logo: user.get('avatar')
        };
      });
      this.set('searchResults', results);
    }, (e) => {
      if (this.isDestroyed) { return; }
      this.set('hasError', true);
      throw e;
    }).finally(() => {
      if (this.isDestroyed) { return; }
      this.set('isLoading', false);
    });
  },

  _clearSearch() {
    this.set('searchResults', null);
    this.set('query', '');
    this.set('isLoading', false);
    this.set('hasError', false);
  },

  _trackModerator(user, eventName) {
    this.get('store').findRecord('user', user.name).then(result => {
      if (this.isDestroyed) { return; }
      let trackingObject = {
        community_id: this.get('communities.communityInfo._id'),
        community_name: this.get('communities.communityInfo.name'),
        login: this.get('session.userData.login'),
        is_subadmin: this.get('session.userData.is_admin'),
        is_admin: this.get('session.userData.is_staff'),
        target_login: user.name,
        is_target_subadmin: result.get('type') === 'admin',
        is_target_admin: result.get('type') === 'staff'
      };
      this.get('tracking').trackEvent({
        services: ['spade'],
        event: eventName,
        data: trackingObject
      });
    });
  },

  actions: {
    search(query) {
      if (this.get('query') === query) {
        return;
      }

      this.set('isLoading', true);
      this.set('query', query);
      query = query.trim().toLowerCase();

      if (!query) {
        this._clearSearch();
        return;
      }

      run.debounce(this, '_search', query, 500);
    },

    addModerator(user) {
      this.get('communities').addModerator(user._id)
      .then(() => {
        if (this.isDestroyed) { return; }
        this.get('moderators').addObject(user);
        this._trackModerator(user, 'community_moderator_add');
      }, error => {
        if (this.isDestroyed) { return; }
        throw error;
      });
      this._clearSearch();
    },

    removeModerator(user) {
      this.get('communities').removeModerator(user._id)
      .then(() => {
        if (this.isDestroyed) { return; }
        let moderators = this.get('moderators').filter(mod => {
          return (mod._id === user._id) ? false : true;
        });
        this.set('moderators', moderators);
        this._trackModerator(user, 'community_moderator_remove');
      }, error => {
        if (this.isDestroyed) { return; }
        throw error;
      });
      this._clearSearch();
    }
  }
});
