/*
	reducer for social data's like liking data
*/
import _ from 'lodash';
import {
	GET_PLAYLIST_LIKES_SUCCESS,
	GET_ALBUM_LIKES_SUCCESS,
	GET_SOCIAL_NAMES_SUCCESS,
	SUBMIT_LOGIN_SUCCESS,
} from '../store/actionTypes';

const initialState = {
	playlists: { like: {} },
	albums: { pictureIds: {} },
	friends: {},
};

export const socialData = (state = initialState, action) => {
	switch (action.type) {
		case GET_PLAYLIST_LIKES_SUCCESS: {
			const { playlistId, slides, data } = action.payload;
			const like = {};
			const removedLikes = {};
			let resetAllLikes = false;
			if (slides && slides.length) {
				slides.forEach((item) => {
					removedLikes[item.uniqueHtmlId.split(':')[0]] = undefined;
				});
			} else {
				resetAllLikes = true;
			}
			data.like.forEach((item) => {
				const likedByMapped = {};
				item.likedBy.forEach(i => { likedByMapped[i] = true; });
				like[item.mediaItemId] = {
					...item,
					likedByMapped,
					// ...item.lastUpdated,
				};
			});
			return {
				...state,
				playlists: {
					...state.playlists,
					[playlistId]: {
						...data,
						like: {
							...((state.playlists[playlistId] && !resetAllLikes) ? state.playlists[playlistId].like : {}),
							...removedLikes,
							...like,
						},
					},
				},
			};
		}
		case GET_ALBUM_LIKES_SUCCESS: {
			const { contents, data } = action.payload;
			const like = {};
			const removedLikes = {};
			contents.forEach((item) => {
				removedLikes[item.id] = undefined;
			});
			data.pictureIds.forEach((item) => {
				like[item] = true;
			});
			return {
				...state,
				albums: {
					...state.albums,
					pictureIds: {
						...state.albums.pictureIds,
						...removedLikes,
						...like,
					},
				},
			};
		}
		case GET_SOCIAL_NAMES_SUCCESS: {
			const { data } = action.payload;
			const friends = _(data.friends)
				.keyBy('userProfileId')
				.value() || {};
			return {
				...state,
				friends,
			};
		}
		case SUBMIT_LOGIN_SUCCESS:
			// reset social data cache on login
			return initialState;
		default: return state;
	}
};
