import React, { useEffect, useState, useRef, useImperativeHandle } from 'react';
import './index.less';
import JSMpeg from './jsmpeg-player.js';

type Props = {
  coverImg?: string;
  videoSrc: string;
  options?: {};
};

const TsVideo = React.forwardRef(
  ({ coverImg, videoSrc, options }: Props, ref) => {
    const tsVideo = useRef(null);
    const playerRef = useRef<any>();
    useImperativeHandle(ref, () => playerRef.current);
    var [isCover, setIsCover] = useState(true);
    useEffect(() => {
      const initTs = () => {
        let canvas = tsVideo.current.querySelector('.tsVideo-content');
        canvas.style.display = 'none';
        playerRef.current = new JSMpeg.VideoElement(
          canvas,
          videoSrc,
          {
            canvas,
            autoplay: true,
            loop: true,
            progressive: false, //是否为chunk
            chunkSize: 1024 * 1024,
            control: false,
            poster: coverImg,
            preserveDrawingBuffer: true,
            decodeFirstFrame: true,
            disableGl: true,
            audio: true,
          },
          {
            onPlay: () => {
              setIsCover(false);
              canvas.style.display = 'block';
            },
            ...options,
          },
        );
      };
      initTs();
      return () => {
        playerRef.current?.destroy();
      };
    }, [videoSrc]);

    return (
      <div ref={tsVideo} className="tsVideo">
        {isCover && coverImg ? (
          <img className="tsVideo-image" src={coverImg} />
        ) : null}
        <canvas className="tsVideo-content"></canvas>
      </div>
    );
  },
);

export { TsVideo };
