import _ from 'lodash';

export const formatAvatarObj = (item) => (_.isEmpty(item) ? {} : ({
	[item.username]: {
		avatar: {
			url: _.get(item, 'avatar.uri', null) || _.get(item, 'avatar.url', null),
		},
	},
}));

// Getting all playlist slides and flattening them with avatar data into one array
export const getMultiplePlaylistsContent = (state) => {
	const { playlists: { playlists: propsPlaylists }, frames: { frames, currentFrameId } } = state;
	if (_.isEmpty(propsPlaylists)) return [];

	const currentFrame = (!_.isEmpty(frames)) ? _.find(frames, { id: currentFrameId }) || {} : {};
	const currentFramePlaylists = _.filter(propsPlaylists, (p) => _.find(currentFrame.playlists, { id: p.id }));
	const playlistsWithPhotos = _.filter(currentFramePlaylists, ({ count: c }) => c > 0);

	const slides = _.map(playlistsWithPhotos, (playlist) => {
		if (_.isEmpty(playlist.slides)) return [];

		const contributors = _.get(playlist, 'sharing.contributors', []);
		const owner = _.get(playlist, 'sharing.owner', {});
		const contributorAvatars = contributors.reduce((acc, contrib) => (
			{ ...acc, ...formatAvatarObj(contrib) }
		), { ...formatAvatarObj(owner) });
		const isPlaylistOwner = _.get(playlist, 'sharing.is_owner', true);
		const playlistId = playlist.id;

		return _.map(playlist.slides, (photo) => (
			{
				...photo,
				isPlaylistOwner,
				playlistId,
				userAvatar: contributorAvatars[photo.username],
			}
		));
	});

	const loaded = _.reduce(playlistsWithPhotos, (acc, playlist) => ({
		...acc,
		[playlist.id]: {
			loadedCount: _.get(playlist, 'slides', []).length,
			totalCount: playlist.count,
		},
	}), {});

	const counted = _.reduce(playlistsWithPhotos, (a, i) => (i.count + a), 0);

	return {
		content: _.flatten(slides),
		loadedContent: loaded,
		count: counted,
	};
};
