import { Dimensions, DimensionValue, Platform, ViewStyle } from "react-native";
import { Edge } from "react-native-safe-area-context";

export type DimensionsT = {
  width: number | string;
  height: number | string | undefined;
  aspectRatio?: number;
};

export type Configuration = {
  [key: string]: any;
  tablet_landscape_sidebar_width?: string;
  tablet_landscape_player_container_background_color?: string;
};

// This is safe, remembering screen dimensions once as they do not change during runtime
// TODO: consider sharing screen orientation as a shared function for the app
const { width: SCREEN_WIDTH, height: SCREEN_HEIGHT } = Dimensions.get("screen");

export const getWindowDimensions = () => {
  const { width, height } = Dimensions.get("window");

  return { width, height };
};

export const getMaxWindowDimension = () => {
  const { width, height } = getWindowDimensions();

  return Math.max(width, height);
};

export const getMinWindowDimension = () => {
  const { width, height } = getWindowDimensions();

  return Math.min(width, height);
};

export const getScreenAspectRatio = () => {
  const longEdge = Math.max(SCREEN_WIDTH, SCREEN_HEIGHT);
  const shortEdge = Math.min(SCREEN_WIDTH, SCREEN_HEIGHT);

  return longEdge / shortEdge;
};

export const getEdges = (
  isTablet: boolean,
  isInlineModal: boolean
): readonly Edge[] => {
  if (isTablet) {
    return ["top"];
  }

  if (!isInlineModal && Platform.OS === "android") {
    return [];
  }

  return ["top"];
};

export const getBaseDimensions = (
  isInlineModal: boolean,
  isTabletLandscape: boolean,
  tabletWidth: DimensionValue
): ViewStyle => ({
  width: isInlineModal && isTabletLandscape ? tabletWidth : "100%",
  height: undefined,
});

export const calculateAspectRatio = (
  isInlineModal: boolean,
  pip?: boolean
): number => {
  return !isInlineModal && !pip ? getScreenAspectRatio() : 16 / 9;
};

export const getPlayerDimensions = (
  baseDimensions: ViewStyle,
  aspectRatio: number
): ViewStyle => ({
  ...(baseDimensions as any),
  width: baseDimensions.width,
  aspectRatio,
});

export const getContainerDimensions = (
  baseDimensions: ViewStyle,
  aspectRatio?: string | number
): ViewStyle => ({
  ...baseDimensions,
  aspectRatio,
});
