import JSONSerializer from 'ember-data/serializers/json';

export default JSONSerializer.extend({

  normalizeResponse(store, primaryModelClass, { results }) {
    let normalizedResults = results.map((result) => {
      // Algolia has slave indexes for different sorting options appened with
      // _by_xxx. We remove the _by_ suffix from the index to ensure the results
      // map to the proper category.
      result.index = result.index.split('_by_')[0];

      // We do 2 requests to Algolia for each type. The 2nd request asks for no
      // hitsPerPage and is used to get a total unfiltered count of hits.
      if (result.hitsPerPage === 0) {
        return { nbHits: result.nbHits, index: result.index };
      }

      // For a paginated result we append the new hits to existing ones.
      if (result.page > 0) {
        let record = store.peekRecord('search', result.index);
        result.hits.unshift(...record.get('hits'));
      }

      return result;
    });

    let jsonAPI = {
      data: normalizedResults.map((result) => {
        return {
          type: 'search',
          id: result.index,
          attributes: this.extractAttributes(primaryModelClass, result)
        };
      })
    };

    return jsonAPI;
  },

  keyForAttribute(attr) {
    if (attr === 'totalHitCount') {
      return 'nbHits';
    }

    return this._super(...arguments);
  },

  pushPayload(store, payload) {
    let modelClass = store.modelFor('search');
    store.push(this.normalizeResponse(store, modelClass, payload));
  }
});
