import { SET_SELECTED_LIBRARIES, SET_USER_LIBRARIES } from '../actions'
const initialState = {
userLibraries: [],
selectedLibraries: [],
}
export const libraryReducer = (previousState = initialState, payload) => {
const { type, data } = payload
switch (type) {
case SET_USER_LIBRARIES: {
const newUserLibraryIds = data.map((lib) => lib.id)
const validatedSelection = previousState.selectedLibraries.filter((id) =>
newUserLibraryIds.includes(id),
)
let finalSelection
if (
previousState.selectedLibraries.length === 0 &&
previousState.userLibraries.length === 0
) {
finalSelection = newUserLibraryIds
} else if (newUserLibraryIds.length === 1) {
finalSelection = []
} else {
finalSelection = validatedSelection
}
return {
...previousState,
userLibraries: data,
selectedLibraries: finalSelection,
}
}
case SET_SELECTED_LIBRARIES:
return {
...previousState,
selectedLibraries: data,
}
default:
return previousState
}
}