import * as React from "react";
import { valueOrDefault } from "@intelligentgraphics/ig.utilities";
import { useSessionContext } from "./SessionContext";
const createStateFromSession = (session) => ({
    articles: session.getAllArticles(),
});
export const useArticleState = (session) => {
    const sessionContext = useSessionContext();
    const targetSession = valueOrDefault(session, sessionContext.session);
    const [state, setState] = React.useState(() => createStateFromSession(targetSession));
    React.useEffect(() => {
        const update = () => {
            setState(createStateFromSession(targetSession));
        };
        let timer;
        const debouncedUpdate = () => {
            if (timer !== undefined) {
                clearTimeout(timer);
                timer = undefined;
            }
            timer = setTimeout(update);
        };
        const subscription = targetSession.subscribe({
            ItemCreated: debouncedUpdate,
            ItemConfigured: debouncedUpdate,
            ItemRemoved: debouncedUpdate,
        });
        update();
        return () => {
            subscription.destroy();
        };
    }, [targetSession]);
    return state;
};
const ArticleStateSubscription = props => {
    const articleState = useArticleState(props.session);
    return props.children(articleState);
};
ArticleStateSubscription.displayName = "ArticleStateSubscription";
export default ArticleStateSubscription;
