import * as React from "react";
import { PlayerLifecycleListener, playerManager } from "./index";
import { Player } from "./player";
import { PlayerStateContext } from "@applicaster/zapp-react-native-ui-components/Contexts/PlayerStateContext";

const getControlledPlayer = (playerId, isCasting): Player => {
  if (isCasting) {
    if (!playerId || playerManager.isActivePlayer(playerId)) {
      return playerManager.getCastingReceiver();
    }
  }

  return playerManager.getPlayerWithId(playerId);
};

// For main player ui controls only
export const usePlayer = (playerId?: string): Player => {
  const { playerId: contextPlayerId } = React.useContext(PlayerStateContext);

  const playerIdToUse =
    playerId || contextPlayerId || playerManager.getActivePlayerId();

  const isCasting = playerManager.isCasting();

  const getPlayer = (playerId, isCasting) =>
    getControlledPlayer(playerId, isCasting);

  const [player, setPlayer] = React.useState<Player>(
    getPlayer(playerIdToUse, isCasting)
  );

  React.useEffect(() => {
    if (!playerIdToUse) {
      setPlayer(null);

      return;
    }

    const newPlayer = getPlayer(playerIdToUse, isCasting);

    if (newPlayer) {
      setPlayer(newPlayer);
    }

    return playerManager.addLifecycleListener({
      onRegistered: (player) => {
        if (playerIdToUse === player.playerId) {
          setPlayer(getPlayer(playerIdToUse, playerManager.isCasting()));
        }
      },
      onUnRegistered: (player) => {
        if (playerIdToUse === player.playerId) {
          setPlayer(null);
        }
      },
      onCastingChanged: () => {
        setPlayer(getPlayer(playerIdToUse, playerManager.isCasting()));
      },
    } as PlayerLifecycleListener);
  }, [playerIdToUse]);

  return player;
};
