import { useRef, useEffect } from 'react'
import videojs, { VideoJsPlayer } from 'video.js'

export const useVideo = (src: string): [any, VideoJsPlayer | undefined] => {
  const videoPlayerRef: any = useRef()
  const videoPlayer: { current: VideoJsPlayer | undefined } = useRef()

  useEffect(() => {
    videoPlayer.current = videojs(videoPlayerRef.current, {
      width: 512,
      loop: true,
      controls: true,
      muted: true
    })
    return () => {
      if (videoPlayer.current) videoPlayer.current.dispose()
    }
  }, [])

  useEffect(() => {
    if (videoPlayer.current) {
      const paused = videoPlayer.current.paused()
      videoPlayer.current.src(src)
      if (!paused) videoPlayer.current.play()
    }
  }, [src])

  return [videoPlayerRef, videoPlayer.current]
}
