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

export const PageDesignerContainer = memo(({ children }: { children: JSX.Element | JSX.Element[] }) => {
  const [designer, setDesigner] = useState<PageDesigner>()
  const { getCommApi } = useContext(CreateJsDesignerContext)

  const clear = useCallback(() => {
    setDesigner(old => {
      if (old) {
        old.destroy()
      }
      return undefined
    })
  }, [setDesigner])

  const createDigner = useCallback(
    (div: HTMLDivElement) => {
      const newInst = new PageDesigner(getCommApi(), div)
      setDesigner(old => {
        if (old) {
          old.destroy()
        }
        return newInst
      })
    },
    [getCommApi, setDesigner],
  )

  const value2 = useMemo(
    () => ({
      designer,
      clear,
      createDigner,
    }),
    [designer, clear, createDigner],
  )

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


