import EmbeddedRecordsMixin from 'ember-data/serializers/embedded-records-mixin';
import JSONSerializer from 'ember-data/serializers/json';
import { underscore } from 'ember-string';
import { trimQueryParams } from 'web-client/utilities/url-params';

export default JSONSerializer.extend(EmbeddedRecordsMixin, {
  keyForAttribute: underscore,
  attrs: {
    thumbnail: { deserialize: 'records' }
  },

  normalizeArrayResponse(store, primaryModelClass, payload, id, requestType)  {
    let newPayload = payload.clips;
    newPayload.meta = { cursor: payload._cursor };
    return this._super(store, primaryModelClass, newPayload, id, requestType);
  },

  extractRelationships(modelClass, resourceHash) {
    resourceHash.thumbnail = this._makeThumbnail(resourceHash.id, resourceHash.thumbnails);
    delete resourceHash['thumbnails'];

    return this._super(modelClass, resourceHash);
  },

  normalize(typeClass, hash) {
    hash.broadcaster_display_name = hash.broadcaster.display_name;
    hash.broadcaster_login = hash.broadcaster.name;
    hash.broadcaster_channel_url = hash.broadcaster.channel_url;
    hash.broadcaster_id = hash.broadcaster.id;
    hash.curator_display_name = hash.curator.display_name;
    hash.curator_login = hash.curator.name;
    hash.curator_channel_url = hash.curator.channel_url;
    hash.curator_id = hash.curator.id;

    // Strip tracking query params returned from the API
    if (hash.url) {
      hash.url = trimQueryParams(hash.url);
    }

    if (hash.embed_url) {
      hash.embed_url = trimQueryParams(hash.embed_url);
    }

    return this._super(typeClass, hash);
  },

  _makeThumbnail(clipId, thumbnail) {
    return {
      type: 'sized-image',
      id: `clip-${clipId}-thumbnail`,
      attributes: thumbnail
    };
  }
});
