import { PlayNextState } from "./OverlayObserver/OverlaysObserver";
import { usePlayer } from "./usePlayer";
import * as React from "react";
import { createLogger } from "../../logger";

const { log_verbose } = createLogger({
  category: "General",
  subsystem: "usePlayNextOverlay",
});

export const usePlayNextOverlay = (
  playerId: string = null,
  logId?: string
): PlayNextState => {
  const player = usePlayer(playerId);
  const [event, setEvent] = React.useState<PlayNextState>(null);

  React.useEffect(() => {
    if (!player) {
      setEvent(null);

      return;
    }

    const observer = player.getOverlayObservable();

    if (observer) {
      const observable = observer.getPlayNextObservable();

      const subscription = observable.subscribe((event) => {
        setEvent(event);

        if (logId && event?.entry) {
          log_verbose(
            `${logId}: Received new play next state. title: ${event.entry?.title}, id: ${event.entry?.id}`,
            { event }
          );
        }
      });

      return () => {
        if (subscription) {
          setEvent(null);
          subscription.unsubscribe();
        }
      };
    }
  }, [player]);

  return event;
};
