import RSVP from 'rsvp';
import Service from 'ember-service';
import injectService from 'ember-service/inject';

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

  store: injectService(),
  requests: injectService('twitch-friends-list/requests'),
  presence: injectService('twitch-presence/presence'),
  friends: injectService('twitch-friends-list/friends'),

  _fetchUserData(results) {
    let ids = results.getEach('id'),
        store = this.get('store'),
        promises = [];

    while (ids.length) {
      let batch = ids.splice(0, 100),
          // Fetch user info in batches of 100. We need all the displaynames up
          // front to support quickly filtering friends in-memory.
          promise = store.query('friends-list-user', {
            type: 'user-info',
            ids: batch
          });
      promises.push(promise);
    }

    return promises;
  },

  initializeFriendButton(login) {
    return this.get('store').queryRecord('friends-list-user', {
      type: 'friend-status',
      login: login
    });
  },

  initializeFriendsList() {
    this.get('pubsub').listen();
    return RSVP.hash({
      notifications: this.get('requests').fetchNotificationCount(),
      friends: this.get('store').query('friends-list-user', {
        type: 'friends'
      })
    }).then(results => {
      this.set('friends.isLoading', false);
      return this._fetchUserData(results.friends);
    });
  }
});
