import JSONSerializer from 'ember-data/serializers/json';
import { underscore } from 'ember-string';
import omit from 'web-client/utilities/omit';
import { deserializeChannel } from 'web-client/serializers/channel';

export default JSONSerializer.extend({
  keyForAttribute: underscore,

  attrs: {
    status: { serialize: false }
  },

  primaryKey: '_id',

  serializeBelongsTo(snapshot, json, relationship) {
    // Don't serialize channel, this is included in the URL.
    if (relationship.type !== 'channel') {
      this._super(...arguments);
    }
  },

  normalizeArrayResponse(store, primaryModelClass, payload) {
    let compoundDocument = payload.reduce((accum, event) => {
      let eventDocument = this.normalizeSingleResponse(store, primaryModelClass, event);

      return {
        data: [...accum.data, eventDocument.data],
        included: [...accum.included, ...eventDocument.included]
      };
    }, {
      data: [],
      included: []
    });

    return compoundDocument;
  },

  normalizeSingleResponse(store, primaryModelClass, payload) {
    let eventPayloadWithoutRelationships = omit(payload, 'channel', 'game');
    let eventDocument = this.normalize(primaryModelClass, eventPayloadWithoutRelationships);
    eventDocument.included = [];

    if (payload.channel) {
      eventDocument.data.relationships.channel = {
        data: {
          // Strange but true, we use the channel's name as the ID in the ED cache.
          id: payload.channel.name,
          type: 'channel'
        }
      };
      eventDocument.included.push(deserializeChannel(payload.channel));
    }

    if (payload.game) {
      eventDocument.data.relationships.game = {
        data: {
          id: payload.game._id,
          type: 'game'
        }
      };
      eventDocument.included.push(normalizeGame(payload.game));
    }

    return eventDocument;
  }
});

function normalizeGame(game) {
  return {
    type: 'game',
    id: game._id,
    attributes: {
      _id: game._id,
      name: game.name,
      popularity: game.popularity,
      giantbombId: game.giantbomb_id,
      boxImage: game.box,
      logoImage: game.logo
    }
  };
}
