import type { eventWithTime, listenerHandler } from '@rrweb/types'
import { useEffect, useRef } from 'react'
import { record } from 'rrweb'

interface RrwebRecorderProps {
  onEventBatch: (events: eventWithTime[]) => void
}

export function RrwebRecorder({ onEventBatch }: RrwebRecorderProps) {
  const stopRef = useRef<listenerHandler | null>(null)

  useEffect(() => {
    const events: eventWithTime[] = []

    const stopFn = record({
      emit(event: eventWithTime) {
        events.push(event)

        if (events.length >= 50) {
          onEventBatch(events.splice(0))
        }
      }
    })

    if (stopFn) {
      stopRef.current = stopFn
    }

    return () => {
      if (stopRef.current) {
        stopRef.current()
        stopRef.current = null

        if (events.length > 0) {
          onEventBatch(events)
        }
      }
    }
  }, [onEventBatch])

  return null
}
