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

const UI_CONTEXT = 'community_page';

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

  query: null,
  searchResults: null,
  hasError: false,
  bannedChannels: [],
  isLoading: false,
  isLoadingBans: false,

  init() {
    this._super(...arguments);

    this.set('isLoadingBans', true);
    this.get('communities').fetchBannedChannels().then(data => {
      if (this.isDestroyed) { return; }
      this.set('bannedChannels', data.banned_users);
      this.set('isLoadingBans', false);
    });
  },

  _getTrackingObject(user) {
    return {
      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'),
      is_community_owner: parseInt(this.get('communities.communityInfo.owner_id')) === this.get('session.userData.id'),
      is_community_mod : parseInt(this.get('communities.communityInfo.owner_id')) !== this.get('session.userData.id'),
      channel: user.name,
      ui_context: UI_CONTEXT
    };
  },

  _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 {
          user_id: user.get('id'),
          name: user.get('login'),
          display_name: user.get('displayName'),
          avatar_image_url: 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);
  },

  _trackUnban(user) {
    let trackingObject = this._getTrackingObject(user);
    this.get('tracking').trackEvent({
      services: ['spade'],
      event: 'community_unban',
      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);
    },

    unbanChannel(user) {
      this.get('communities').unbanUser(user.user_id)
      .then(() => {
        if (this.isDestroyed) { return; }
        this.get('bannedChannels').removeObject(user);
        this._trackUnban(user);
      }, error => {
        if (this.isDestroyed) { return; }
        throw error;
      });
      this._clearSearch();
    },

    addTimeoutCb(data) {
      let trackingObject = this._getTrackingObject(data.user);
      trackingObject.duration = data.duration;
      this.get('tracking').trackEvent({
        event: 'community_timeout',
        data: trackingObject
      });
      this._clearSearch();
    },

    addBanItem(user) {
      let trackingObject = this._getTrackingObject(user);
      this.get('tracking').trackEvent({
        event: 'community_ban',
        data: trackingObject
      });
      this.get('bannedChannels').addObject(user);
      this._clearSearch();
    }
  }
});
