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

export default Service.extend({
  store: injectService(),
  session: injectService(),

  search(q) {
    let users;
    return this.get('store').query('friends-list-user', {
      q,
      type: 'search'
    }).then(_users => {
      users = this._filterResults(_users);
      if (users.length) {
        let promises = this._createRelationshipPromises(users);
        promises.push(this._getUserInfo(users));
        return RSVP.all(promises);
      }
      return users;
    }).then(() => {
      return users;
    });
  },

  searchNoRelationship(q) {
    return this.get('store').query('friends-list-user', {
      q,
      type: 'search'
    });
  },

  _filterResults(users) {
    let currentUserId = this.get('session.userData.id');

    return users.filter(user => {
      return !user.get('isFriend') &&
             user.get('id') !== currentUserId;
    });
  },

  _getUserInfo(users) {
    return this.get('store').query('friends-list-user', {
      ids: users.getEach('id'),
      type: 'user-info'
    });
  },

  _createRelationshipPromises(users) {
    return users.map(user => {
      return this.get('store').queryRecord('friends-list-user', {
        login: user.get('login'),
        type: 'friend-status'
      });
    });
  }
});
