import {
    type ReactNode,
    useEffect,
    useRef
} from "react";
import {
    type IProvider
} from "./Host";

interface IConsumerProps {
    manager: IProvider | null;
    children: ReactNode;
    name?: string;
};

export const Consumer = ({
    children,
    manager,
    name
}: IConsumerProps): null => {
    const key = useRef<string | undefined>(undefined);

    const checkManager = (): void => {
        if (!manager) {
            throw new Error("No portal manager defined");
        }
    };

    const handleInit = (): void => {
        checkManager();
        key.current = manager?.mount(children, name);
    };

    useEffect(() => {
        checkManager();
        manager?.update(key.current, children, name);
    }, [
        children,
        manager,
        name
    ]);

    useEffect(() => {
        handleInit();

        return (): void => {
            checkManager();
            manager?.unmount(key.current);
        };
    }, []);

    return null;
};
