import * as React from "react";
import { noop } from "@applicaster/zapp-react-native-utils/functionUtils";

type withAsyncRenderHOCProps = {
  emitAsyncElementRegistrate?: () => (() => void) | void;
  emitAsyncElementLayout?: () => void;
};

export const withAsyncRenderHOC = <P extends { onAsyncRender: () => void }>(
  Component: React.ComponentType<P>
): React.FC<Omit<P, "onAsyncRender"> & withAsyncRenderHOCProps> => {
  const WithAsyncRender = (
    props: Omit<P, "onAsyncRender"> & withAsyncRenderHOCProps
  ) => {
    const { emitAsyncElementRegistrate = noop, emitAsyncElementLayout = noop } =
      props;

    React.useEffect(() => {
      if (props.emitAsyncElementRegistrate) {
        return emitAsyncElementRegistrate();
      }
    }, []);

    const onAsyncRender = React.useCallback(() => {
      if (props.emitAsyncElementLayout) {
        emitAsyncElementLayout();
      }
    }, [emitAsyncElementLayout]);

    return (
      <Component {...(props as unknown as P)} onAsyncRender={onAsyncRender} />
    );
  };

  return WithAsyncRender;
};
