import JSONSerializer from 'ember-data/serializers/json';
import { underscore } from 'ember-string';

export const COLLECTION_ITEM_ID_DELIMITER = '+';

export default JSONSerializer.extend({
  keyForAttribute: underscore,
  extractId(modelClass, resourceHash) {
    return `${resourceHash.playlist_id}${COLLECTION_ITEM_ID_DELIMITER}${resourceHash._id}`;
  },
  normalizeArrayResponse(store, primaryModelClass, payload, id, requestType) {
    if (Array.isArray(payload.items)) {
      payload.items = payload.items.map((item, index) => {
        item.playlist_id = payload._id;
        // For now (until we support pagination) the position can be determined
        // by the response from the server directly
        item.position = index;
        return item;
      });
    }

    return this._super(store, primaryModelClass, payload.items, id, requestType);
  },

  extractRelationships(modelClass, resourceHash) {
    return {
      [resourceHash.item_type]: {
        data: { type: resourceHash.item_type, id: resourceHash.item_id }
      },
      owner: {
        data: { type: 'user', id: resourceHash.owner.name }
      },
      playlist: {
        data: { type: 'video-playlist', id: resourceHash.playlist_id }
      }
    };
  }
});
