import { memo, useCallback, useContext, useMemo, useState } from "react"
import { PageLoader } from "./PageLoader"
import { CreateJsDesignerContext, PageLoaderContainerContext } from "../types"

export const PageLoaderContainer = memo(({ children,adaptMode }: { children: JSX.Element | JSX.Element[],adaptMode ?:number }) => {
  const [loader, setLoader] = useState<PageLoader>()
  const { getCommApi } = useContext(CreateJsDesignerContext)
  const clear = useCallback(() => {
    setLoader(old => {
      if (old) {
        old.destroy()
      }
      return undefined
    })
  }, [setLoader])

  const createLoader = useCallback(
    (div: HTMLDivElement) => {
      const newInst = new PageLoader(getCommApi(), div,adaptMode)
      setLoader(old => {
        if (old) {
          old.destroy()
        }
        return newInst
      })
    },
    [getCommApi, setLoader],
  )

  const value2 = useMemo(
    () => ({
      loader,
      clear,
      createLoader,
    }),
    [loader, clear, createLoader],
  )

  return <PageLoaderContainerContext.Provider value={value2}>{children}</PageLoaderContainerContext.Provider>
})


