/*
	Dedicated loading reducer for fetching/sending data via redux-saga
*/

import {
	GET_ALBUMS,
	GET_ALBUMS_SUCCESS,
	GET_ALBUMS_ERROR,
	GET_ALBUM_CONTENT,
	GET_ALBUM_CONTENT_SUCCESS,
	GET_ALBUM_CONTENT_ERROR,
	GET_PLAYLISTS,
	GET_PLAYLISTS_SUCCESS,
	GET_PLAYLISTS_ERROR,
	GET_PLAYLIST_CONTENT,
	GET_PLAYLIST_CONTENT_SUCCESS,
	GET_PLAYLIST_CONTENT_ERROR,
	SET_PLAYLIST_SORT,
	SET_PLAYLIST_SORT_SUCCESS,
	SET_PLAYLIST_SORT_ERROR,
	UPDATE_PLAYLIST_CONTENT_SEQ,
	UPDATE_PLAYLIST_CONTENT_SEQ_SUCCESS,
	UPDATE_PLAYLIST_CONTENT_SEQ_ERROR,
} from '../store/actionTypes';

const initialState = {
	albums: {
		getAlbums: false,
		getAlbumContent: false,
	},
	playlists: {
		getPlaylists: false,
		getPlaylistContent: false,
		sortPlaylist: false,
	},
};

const startLoading = ({ state, reducer, property }) => ({
	...state,
	[reducer]: {
		...state[reducer],
		[property]: true,
	},
});
const stopLoading = ({ state, reducer, property }) => ({
	...state,
	[reducer]: {
		...state[reducer],
		[property]: false,
	},
});

export const loading = (state = initialState, action) => {
	switch (action.type) {
		case GET_ALBUMS: return startLoading({ state, reducer: 'albums', property: 'getAlbums' });
		case GET_ALBUMS_SUCCESS:
		case GET_ALBUMS_ERROR: return stopLoading({ state, reducer: 'albums', property: 'getAlbums' });
		case GET_ALBUM_CONTENT: return startLoading({ state, reducer: 'albums', property: 'getAlbumContent' });
		case GET_ALBUM_CONTENT_SUCCESS:
		case GET_ALBUM_CONTENT_ERROR: return stopLoading({ state, reducer: 'albums', property: 'getAlbumContent' });
		case GET_PLAYLISTS: return startLoading({ state, reducer: 'playlists', property: 'getPlaylists' });
		case GET_PLAYLISTS_SUCCESS:
		case GET_PLAYLISTS_ERROR: return stopLoading({ state, reducer: 'playlists', property: 'getPlaylists' });
		case GET_PLAYLIST_CONTENT: return startLoading({ state, reducer: 'playlists', property: 'getPlaylistContent' });
		case GET_PLAYLIST_CONTENT_SUCCESS:
		case GET_PLAYLIST_CONTENT_ERROR: return stopLoading({ state, reducer: 'playlists', property: 'getPlaylistContent' });
		case UPDATE_PLAYLIST_CONTENT_SEQ:
		case SET_PLAYLIST_SORT: return startLoading({ state, reducer: 'playlists', property: 'sortPlaylist' });
		case UPDATE_PLAYLIST_CONTENT_SEQ_SUCCESS:
		case UPDATE_PLAYLIST_CONTENT_SEQ_ERROR:
		case SET_PLAYLIST_SORT_SUCCESS:
		case SET_PLAYLIST_SORT_ERROR: return stopLoading({ state, reducer: 'playlists', property: 'sortPlaylist' });
		default: return state;
	}
};
