import { StateT, Ressource } from './provider'

import { createContext, useContext, Dispatch } from 'react'

export type Action =
  | { type: 'clickOnDir'; ressource: Ressource }
  | { type: 'defaultState' }

export type ReducerCtxT = {
  state: StateT
  dispatch: Dispatch<Action>
}

export const ReducerCtx = createContext<Partial<ReducerCtxT>>({})

export const useReducerCtx = () => useContext(ReducerCtx)

export function reducer(state: StateT, action: Action): StateT {
  switch (action.type) {
    case 'clickOnDir': {
      const { ressources } = state

      const newRessourcesFn =
        (selectedDir: Ressource) => (childrenId: number[]) =>
          ressources.map(ressource =>
            ressource.id === selectedDir.id
              ? { ...ressource, isOpen: !selectedDir.isOpen }
              : childrenId.includes(ressource.id)
              ? childrenId.push(ressource.id) && {
                  ...ressource,
                  isVisible: !selectedDir.isOpen,
                }
              : ressource,
          )

      const newRessources = newRessourcesFn(action.ressource)([
        ...action.ressource.childrenIds,
      ])

      return {
        ...state,
        ressources: newRessources,
      }
    }

    case 'defaultState': {
      const { ressources, config } = state

      const newRessources = ressources.map(res =>
        res.depth > config.defaultDepth
          ? { ...res, isVisible: false, isOpen: false }
          : res,
      )

      return {
        ...state,
        ressources: newRessources,
      }
    }

    default:
      state
  }
}