import ApplicationSerializer from './application';
import { deserializeChannel } from 'web-client/serializers/channel';
import { deserializeStream } from 'web-client/serializers/stream';

let _channelRelationship = (channel) => {
  return {
    type: 'channel',
    id: channel.name
  };
};

let _streamRelationship = (stream) => {
  return {
    type: 'stream',
    id: stream.channel.name
  };
};

export function deserializeRecommendedStreamsIncluded(recommendedStreams) {
  let included = [];

  recommendedStreams.forEach((recommendedStream) => {
    // delete channel flag to prevent overwriting of channel.js model with hard
    // coded false
    delete recommendedStream.channel.partner;

    included.push(deserializeChannel(recommendedStream.channel));

    recommendedStream.streams.forEach((stream) => {
      let channel = stream.channel;

      // delete channel falg to prevent overwriting of channel.js model with
      // hard coded false
      delete channel.partner;

      included.push(deserializeStream(stream));
      included.push(deserializeChannel(channel));
    });
  });

  return included;
}

export function deserializeRecommendedStreams(recommendedStreams) {
  return recommendedStreams.map((recommendedStream, index) => {
    let attributes = recommendedStream;

    attributes.rank = index;
    attributes.fetched_at = Date.now();

    return {
      id: recommendedStream.channel.name,
      type: 'recommended-stream',
      attributes: attributes,
      relationships : {
        channel: {
          data: _channelRelationship(recommendedStream.channel)
        },
        streams: {
          data: recommendedStream.streams.map((stream) => {
            return _streamRelationship(stream);
          })
        }
      }
    };
  });
}

export default ApplicationSerializer.extend({
  normalizeQueryResponse(store, type, payload) {
    let data = deserializeRecommendedStreams(payload.recommended_streams);
    let included = deserializeRecommendedStreamsIncluded(payload.recommended_streams);

    return this._super(store, type, {data, included});
  }
});
