import React from "react";
import { useIsTabletLandscape } from "../device/useMemoizedIsTablet";
import { usePlayerManager } from "./hooks/usePlayerManager";
import { useChangeOrientation } from "./hooks/useChangeOrientation";
import { useSetupInitialOrientationForLandscape } from "./hooks/useSetupInitialOrientationForLandscape";

import { transitToOnlyPortrait, transitToOnlyLandscape } from "./utils";

type Props = {
  docked: boolean;
  toggleFullscreen: (params: { fullscreen: boolean }) => void;
  skipAllEffects: boolean;
  skipInitialOrientationEffects: boolean;
  orientationShouldBeLandscape: boolean;
  isRunningPlayNext: boolean;
};

export const useMobileOrientationEffect = ({
  toggleFullscreen,
  docked,
  skipAllEffects,
  skipInitialOrientationEffects,
  orientationShouldBeLandscape,
  isRunningPlayNext,
}: Props) => {
  const [locked, setLock] = React.useState(false);

  const isTabletLandscape = useIsTabletLandscape();

  useChangeOrientation({
    onTransitToPortrait: () => {
      toggleFullscreen({ fullscreen: false });
    },

    onTransitToLandscape: () => {
      toggleFullscreen({ fullscreen: true });
    },
    skipAllEffects: skipAllEffects || locked,
    isPortrait: !orientationShouldBeLandscape,
    docked,
  });

  usePlayerManager({
    onClose: () => {
      if (!isTabletLandscape) {
        transitToOnlyPortrait();
      }
    },
    onFullscreenPlayerWillPresent: () => {
      if (!isTabletLandscape) {
        transitToOnlyLandscape();
      }
    },

    onFullscreenPlayerWillDismiss: () => {
      if (!isTabletLandscape) {
        transitToOnlyPortrait();
      }
    },
    onEnded: () => {
      if (!isTabletLandscape && isRunningPlayNext === false) {
        transitToOnlyPortrait();
      }
    },
    toggleLock: ({ locked }) => {
      setLock(locked);
    },
    skipAllEffects,
    isRunningPlayNext,
  });

  useSetupInitialOrientationForLandscape({
    orientationShouldBePortrait: !orientationShouldBeLandscape,
    skipInitialOrientationEffects,
  });
};
