import { useCallback, useEffect, useState } from 'react'
import KetchupClient from 'ketchup-client'

export type Dispatch<Action> = (action: Action, timestamp?: number) => void

export default function useKetchup<State, Action>(
  url: string,
  reducer: (state: State, action: Action) => State,
): [State | undefined, Dispatch<Action>] {
  const [proj, setProj] = useState<State>()
  const [kc, setKc] = useState<KetchupClient<State, Action>>()

  useEffect(() => {
    const newKc = new KetchupClient(url, reducer)
    setKc(newKc)
    newKc.on('projection', setProj)
    return () => { newKc.off('projection', setProj) }
  }, [url, reducer])

  const dispatch = useCallback((a, ts) => kc?.dispatch(a, ts), [kc])
  return [proj, dispatch, /* connected */]
}
