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

export default JSONAPISerializer.extend({
  keyForAttribute: underscore,

  // any underscored keys on the root object are assumed to be metadata.
  extractMeta(store, type, payload) {
    let meta = {};

    Object.keys(payload).forEach(k => {
      if (k !== '_id' && k[0] === '_') {
        meta[k.slice(1)] = payload[k];
        delete payload[k];
      }
    });

    // api.request uses Twitch.api and expects paths but meta data most likely contains full URLs with protocol and host
    if (meta.links) {
      Object.keys(meta.links).forEach(k => {
        let link = meta.links[k];
        meta.links[k] = link.split('twitch.tv')[1] || link;
      });
    }

    return meta;
  }
});
