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

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

type withAsyncRenderHOCT = (
  Component: React.ComponentType<{ onAsyncRender: () => void }>
) => React.FC<withAsyncRenderHOCProps>;

export const withAsyncRenderHOC: withAsyncRenderHOCT = (Component) => {
  const WithAsyncRender = (props: 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} onAsyncRender={onAsyncRender} />;
  };

  return WithAsyncRender;
};
