import * as React from "react";
import { Player } from "./player";
import { usePlayer } from "./usePlayer";

type PlayerState = {
  currentTime: number;
  duration: number;
  seekableDuration: number;
  isLive: boolean;
  isPaused: boolean;
  isBuffering: boolean;
  isReadyToPlay: boolean;
};

export const usePlayerState = (
  listenerId: string,
  playerId?: string
): PlayerState => {
  const [state, setState] = React.useState<PlayerState>({
    currentTime: null,
    duration: null,
    seekableDuration: null,
    isLive: null,
    isPaused: null,
    isBuffering: false,
    isReadyToPlay: false,
  });

  const player: Player = usePlayer(playerId);

  const onPlayerChangeState = React.useCallback(() => {
    setState({
      currentTime: player.getContentPosition(),
      duration: player.getDuration(),
      seekableDuration: player.getSeekableDuration(),
      isLive: player.isLive(),
      isPaused: player.isPaused(),
      isBuffering: player.isBuffering(),
      isReadyToPlay: player.isReadyToPlay(),
    });
  }, [player]);

  React.useEffect(() => {
    if (player) {
      onPlayerChangeState();

      return player.addListener({
        id: listenerId,
        listener: {
          onVideoProgress: onPlayerChangeState,
          onVideoLoad: onPlayerChangeState,
          onBufferStart: onPlayerChangeState,
          onBufferComplete: onPlayerChangeState,
          onPlayerPause: onPlayerChangeState,
          onPlayerResume: onPlayerChangeState,
          onPlayerSeekComplete: onPlayerChangeState,
        },
      });
    }
  }, [player]);

  return state;
};
