import { useEffect, useRef, useState } from "react";
import { useScript } from "../../../../hook";
import "./index.less";

export interface IVideo {
  fileID: string;
  appID: string;
  psign?: string;
  className?: string;
}

interface IProps {
  video: IVideo | null;
}

/**
 * demo页面：https://tcplayer.vcube.tencent.com/
 *
 * 1. fill填满变形，cover等比例会裁剪, contain等比例有黑边
 * 2. TCPlayer('container', video)如果video为空，初始化会失败
 */
function Player(props: IProps) {
  const playerRef = useRef<any>();
  const [libReady, setLibReady] = useState(false);

  useScript(
    ["/player/libs/hls.min.0.13.2m.js", "/player/tcplayer.v4.7.2.min.js"],
    () => {
      console.log("[tcplayer] libs ready...");
      setLibReady(true);
    }
  );

  useEffect(() => {
    if (libReady) {
      const TCPlayer = (window as any).TCPlayer;
      playerRef.current = TCPlayer("player", {
        // fileID: "243791579995468466",
        // appID: "1500018521",
        ...props.video,
        plugins: {
          ContinuePlay: {
            auto: true,
          },
        },
      });
      console.log("[tcplayer] init success...");
    }
  }, [libReady]);

  useEffect(() => {
    if (props.video) {
      console.log("[tcplayer] video change", props.video);
      playerRef.current.loadVideoByID(props.video);
    }
  }, [props.video]);

  return (
    <video
      onContextMenu={(e) => e.preventDefault()}
      id="player"
      style={{ width: "100%", height: "100%", objectFit: "contain" }}
      preload="auto"
      playsInline
    ></video>
  );
}

export default Player;
