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

const VideoPlayer = ({
  getVideoHandle,
  src
}: {
  getVideoHandle: (videoHandle: VideoJsPlayer) => void;
  src: string;
}) => {
  const videoPlayerRef = useRef();
  const video: { current: VideoJsPlayer | undefined } = useRef();

  useEffect(() => {
    const tmp = videojs(videoPlayerRef.current, {
      width: 320,
      loop: true,
      controls: true
    });
    getVideoHandle(tmp);
    video.current = tmp;
    return () => {
      if (tmp) tmp.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 as any} className="video-js" />
    </div>
  );
};

export default VideoPlayer;
