import AudreySerializer from './audrey';
import { normalizeReactions } from '../utilities/reactions';

export default AudreySerializer.extend({
  readMeta(payload) {
    return {
      total: payload._total,
      cursor: payload._cursor,
      topic: payload._topic,
      disabled: payload._disabled
    };
  },

  getRootNode(payload) {
    let returnPayload =  payload;

    if (payload.hasOwnProperty('posts')) {
      let posts = payload.posts || [];
      for (let i = 0; i < posts.length; i++) {
        let post = posts[i];
        post = this.normalizePost(post);
      }
      returnPayload = posts;
    }
    return returnPayload;
  },

  pushPayload (store, payload) {
    payload.reactions = normalizeReactions(payload.reactions);
    let postDocument = store.normalize('post', payload);
    return store.push(postDocument);
  },


  normalizeCreateRecordResponse(store, modelClass, payload, id, requestType) {
    return this._super(store, modelClass, payload.post, id, requestType);
  },

  normalizeSingleResponse(store, modelClass, payload, id, requestType) {
    if (payload.reactions) {
      payload.reactions = normalizeReactions(payload.reactions);
    }
    payload = this.normalizePost(payload);
    return this._super(store, modelClass, payload, id, requestType);
  },

  normalizeArrayResponse(store, modelClass, payload, id, requestType) {
    if (payload.posts) {
      payload.posts.forEach(post => {
        post.reactions = normalizeReactions(post.reactions);
      });
    }
    return this._super(store, modelClass, payload, id, requestType);
  },

  normalizePost(post) {
    if (post.comments) {
      post.comments_cursor = post.comments._cursor;
      post.comments_total = post.comments._total;
      post.comments = post.comments.comments;
    }
    return post;
  }
});
