import { useCallback, useContext } from 'react'
import { ApiServerContext } from '../context/ApiServerContext'

const useViewMode = (componentName, defaultMode = 'list') => {
  const { userSettings, updateUserSettings } = useContext(ApiServerContext)
  const viewMode = userSettings.viewMode[componentName] ?? defaultMode

  const setViewMode = useCallback(
    (nextMode) => {
      const mode =
        typeof nextMode === 'function' ? nextMode(viewMode) : nextMode
      updateUserSettings('viewMode', componentName, mode)
    },
    [componentName, updateUserSettings, viewMode]
  )

  return [viewMode, setViewMode]
}

export default useViewMode
