import type { IDisposable } from "monaco-editor"
import { useCallback, useEffect, useRef } from "react"

export function useDisposable(fn: () => IDisposable | void, deps: any[]) {
  const register = useDisposables()
  useEffect(() => {
    const disposable = fn()
    if (disposable) {
      register(disposable)
      return () => disposable.dispose()
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, deps)
}

export function useDisposables() {
  const disposables = useRef<IDisposable[]>([])

  const register = useCallback((...disposable: IDisposable[]) => {
    disposables.current.push(...disposable)
  }, [])

  useEffect(
    () => () => {
      disposables.current.forEach(disposable => disposable.dispose())
      disposables.current = []
    },
    [],
  )

  return register
}
