import { useEffect, useRef } from 'react'
import { DOMAttachableStream } from '@zocks-communications/client-sdk-js'

const useMedia = <T extends HTMLMediaElement>(stream: DOMAttachableStream | null) => {
  const mediaRef = useRef<T>(null)

  useEffect(() => {
    const currentRef = mediaRef.current
    if (stream && currentRef) {
      stream.attach(currentRef)
      return () => stream.detach(currentRef)
    }
  }, [stream])

  return {
    mediaRef,
  }
}

export const useVideo = (videoStream: DOMAttachableStream | null) => {
  const { mediaRef: videoRef } = useMedia<HTMLVideoElement>(videoStream)
  return {
    videoRef,
  }
}

export const useAudio = (audioStream: DOMAttachableStream | null) => {
  const { mediaRef: audioRef } = useMedia<HTMLAudioElement>(audioStream)
  return {
    audioRef,
  }
}
