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