/**
 * project reducer
 */
import { applicationState } from "../../state"
import { clone } from "ramda"
import reducerFromMap from "@racletteCore/lib/reducerFromMap"

const addProjectToList = (projects, project) => {
  projects[project._id] = project._source
}
// map instead of switch statement
const reducerMap = {
  init: () => applicationState.projects,
  "projects/add": (state, action) => {
    if (!action.payload) {
      return
    }
    const newState = clone(state)

    if (Array.isArray(action.payload)) {
      action.actionResult.added = action.payload
      action.payload.forEach((project) => addProjectToList(newState, project))
    } else {
      action.actionResult.added.push(action.payload)
      addProjectToList(newState, action.payload)
    }

    return newState
  },
  "projects/update": (state, action) => {
    const { projectId, payload } = action
    const newState = clone(state)

    if (!projectId) {
      return state
    }
    newState[projectId] = payload

    return newState
  },
}

const projectsReducers = reducerFromMap(reducerMap)

export default projectsReducers
