import JSONSerializer from 'ember-data/serializers/json';
import EmbeddedRecordsMixin from 'ember-data/serializers/embedded-records-mixin';
import { underscore } from 'ember-string';

import { COLLECTION_BASE } from 'web-client/adapters/video-playlist';

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

  normalizeQueryResponse(store, primaryModelClass, payload, id, requestType) {
    let newPayload = payload.collections;
    newPayload.meta = { cursor: payload._cursor };
    return this._super(store, primaryModelClass, newPayload, id, requestType);
  },
  extractRelationships(modelClass, resourceHash) {
    let hash = {
      owner: this._makeOwner(resourceHash.owner.name)
    };

    if(resourceHash.thumbnails) {
      hash.thumbnail = this._makeThumbnail(resourceHash._id, resourceHash.thumbnails);
    }

    if(resourceHash.items_count > 0) {
      hash.items = this._makeItems(resourceHash._id);
    }

    return hash;
  },

  _makeThumbnail(playlistId, thumbnail) {
    return {
      data: {
        type: 'sized-image',
        id: `video-playlist-${playlistId}-thumbnail`,
        attributes: thumbnail
      }
    };
  },

  _makeOwner(ownerId) {
    return {
      data: { type: 'user', id: ownerId }
    };
  },

  _makeItems(id) {
    return {
      links : {
        related: `${COLLECTION_BASE}/${id}/items`
      }
    };
  }
});
