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

interface IVideoPlayer {
  src: string
  getVideoHandle: (videoHandle: VideoJsPlayer) => void
}

const VideoPlayer = ({ getVideoHandle, src }: IVideoPlayer) => {
  const videoPlayerRef: any = useRef()
  const video: { current: VideoJsPlayer | undefined } = useRef()

  /**
   * Initial effect creates the player and returns a handle
   * to the
   */
  useEffect(() => {
    const videoPlayer = videojs(videoPlayerRef.current, {
      width: 512,
      loop: true,
      controls: true,
      muted: true
    })
    getVideoHandle(videoPlayer)
    video.current = videoPlayer
    return () => {
      if (videoPlayer) videoPlayer.dispose()
    }
  }, [])

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

  return (
    <div data-vjs-player>
      <video ref={videoPlayerRef} className='video-js vjs-16-9' />
    </div>
  )
}

export default VideoPlayer
