"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var React = require("react");
var ig_utilities_1 = require("@intelligentgraphics/ig.utilities");
var SessionContext_1 = require("./SessionContext");
var createStateFromSession = function (session) { return ({
    articles: session.getAllArticles(),
}); };
exports.useArticleState = function (session) {
    var sessionContext = SessionContext_1.useSessionContext();
    var targetSession = ig_utilities_1.valueOrDefault(session, sessionContext.session);
    var _a = tslib_1.__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 = exports.useArticleState(props.session);
    return props.children(articleState);
};
ArticleStateSubscription.displayName = "ArticleStateSubscription";
exports.default = ArticleStateSubscription;
