import { createContext, useContext } from 'react'

export type Ressource = {
  id: number
  name: string
  path: string
  extension?: string
  isVisible: boolean
  isOpen?: boolean
  isDir: boolean
  childrenIds?: number[]
  depth: number
}

export type Ressources = Ressource[]

export type ConfigT = {
  indent: number
  defaultDepth: number
  defaultRes: Ressource
}

export type StateT = {
  config: ConfigT
  ressources: Ressources
}

export const fetchRessources = async (): Promise<Ressources> =>
  fetch('http://127.0.0.1:2000/api/ressources')
    .then(response => response.json())
    .then(json => json.ressources)

export const initState = async (): Promise<StateT> => {
  const ressources = await fetchRessources()
  return {
    config: {
      indent: 12,
      defaultDepth: 1,
      defaultRes: ressources.at(0),
    },
    ressources,
  }
}

export type DataCtxT = {
  data: StateT
}

export const DataCtx = createContext<Partial<DataCtxT>>({})

export const useDataCtx = () => useContext(DataCtx)