import ApplicationSerializer from './application';

export default ApplicationSerializer.extend({

  keyForAttribute(key) {
   return key;
  },

  normalizeArrayResponse(store, modelClass, payload, id, requestType) {
    let hash = _deserialize(payload);

    return this._super(store, modelClass, hash, id, requestType);
  }

});

let _deserialize = (payload) => {
  let hash = {data: [], included: []};

  payload.offers.forEach((offer) => {
    let id = offer.offerId;
    let relationships = {};

    if (Array.isArray(offer.assets)) {

      let assets = ['ICON', 'THUMBNAIL', 'DETAIL'].map((assetType) => {
        return offer.assets.find((assetPayload) => { return assetPayload.assetType === assetType; });
      })
      .filter((a) => { return !!a; })
      .map((assetPayload) => { return _makeAsset(assetPayload, id); });

      relationships = _makeRelationships(assets);

      hash.included = hash.included.concat(assets);

      delete offer.assets;
    }

    hash.data.push({
      id,
      relationships,
      type: 'offer',
      attributes: offer
    });
  });

  return hash;
};

let _makeAsset = function (asset, id) {
  let type = asset.assetType.toLowerCase();
  return {
    type: 'offer-asset',
    id: `offer-asset-${id}-${type}`,
    attributes: asset
  };
};

let _makeRelationships = (assets) => {
  let result = {};
  assets.forEach((asset) => {
    result[asset.attributes.assetType.toLowerCase()] = {
      data: {
        type: 'offer-asset',
        id: asset.id
      }
    };
  });

  return result;
};
