import Adapter from 'ember-data/adapter';
import injectService from 'ember-service/inject';
import RSVP from 'rsvp';
const BASE_URL = '/api/friendships/users';
const API_LIMIT = 100;

export default Adapter.extend({
  api: injectService(),

  coalesceFindRequests: true,

  // TODO: Remove, see https://git-aws.internal.justin.tv/web/web-client/issues/698
  shouldReloadAll() {
    return true;
  },

  _fetch(ids) {
    ids = ids.join(',');

    return this.get('api').request('get', BASE_URL, { ids })
      .then(response => response.users);
  },

  findRecord(store, type, id) {
    return this._fetch([id]).then(users => users[0]);
  },

  findMany(store, type, ids) {
    // Chunk by API_LIMIT
    let chunkedIds = [];
    for (let i = 0; i < ids.length; i=i+API_LIMIT) {
      chunkedIds.push(ids.slice(i, i+API_LIMIT));
    }
    return RSVP.all(chunkedIds.map(idChunk => this._fetch(idChunk)))
      .then(response => response.reduce((a,b) => a.concat(b)));
  }
});
