import { applicationState } from "../../state"
import { hasOwnProperty } from "@racletteCore/lib/dataHelper"
import { clone } from "ramda"
/**
 * project init
 */
const projectInit = (state, action) => applicationState.ui

const setCompositionAs = (
  state,
  action: {
    payload: { slot: string; compositionId?: string }
  },
) => {
  const { slot, compositionId } = action.payload
  const newState = clone(state)

  if (compositionId) {
    newState[slot] = compositionId
  }

  return newState
}

const unsetComposition = (state, action) => {
  const { slot } = action.payload

  const newState = clone(state)
  newState[slot] = null

  return newState
}

/**
 *  toggle ui
 */
const uiToggle = (state, action) => {
  const uiState = {}

  if (!action.payload.list) {
    return state
  }

  action.payload.list.forEach((field) => {
    if (hasOwnProperty(state, field)) {
      if (state[field]) {
        uiState[field] = false
      }
      if (!state[field]) {
        uiState[field] = true
      }
      if (state[field] === true || state[field] === false) {
        uiState[field] = !state[field]
      }
    }
  })

  return { ...state, ...uiState }
}

/**
 *  update ui
 */
const uiUpdate = (state, action) => ({ ...state, ...action.payload })

export { projectInit, uiToggle, uiUpdate, setCompositionAs, unsetComposition }
