import ApplicationSerializer from './application';

let _makeRelationships = function (payload) {
  let hash = {data: []};

  payload.playlists.forEach(playlist => {
    hash.data.push({
      type:'offline-playlist',
      id: playlist.id
    });
  });

  return hash;
};

let _makeIncluded = function (payload) {
  let channelId = payload.id,
      playlists = payload.playlists,
      included = [];

  playlists.forEach(playlist => {
    let includedObject = {};

    includedObject.type = 'offline-playlist';
    includedObject.id = playlist.id;
    includedObject.attributes = {
      version: playlist.version,
      // Ember converts this to `vodIds` on the model thanks to `keyForAttribute`
      vod_ids: playlist.playlist.vod_ids
    };
    includedObject.relationships = {
      channel: {
        data: {
          type: 'offline-playlist-channel',
          id: channelId
        }
      }
    };
    included.push(includedObject);
  });
  return included;
};

let _deserialize = function (payload) {
  let attributes = {},
      relationships = _makeRelationships(payload),
      included = _makeIncluded(payload),
      hash = {data: {}, included: included};

  Object.keys(payload).forEach(k => {
    if (k !== 'id') {
      attributes[k] = payload[k];
    }
  });

  hash.data = {
    type: 'offline-playlist-channel',
    attributes: attributes,
    id: payload.id,
    relationships: relationships
  };
  return hash;
};


export default ApplicationSerializer.extend({
  normalizeFindRecordResponse(store, type, payload, id) {
    let hash = _deserialize(payload);

    return this._super(store, type, hash, id);
  },
  normalizeUpdateRecordResponse(store, type, payload, id) {
    let hash = _deserialize(payload);

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

});
