"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useCurrentLayout = void 0;
const useCntrlContext_1 = require("../provider/useCntrlContext");
const react_1 = require("react");
const ArticleRectContext_1 = require("../provider/ArticleRectContext");
const useCurrentLayout = () => {
    const { layouts } = (0, useCntrlContext_1.useCntrlContext)();
    const articleRectObserver = (0, react_1.useContext)(ArticleRectContext_1.ArticleRectContext);
    const layoutRanges = (0, react_1.useMemo)(() => {
        const sorted = layouts.slice().sort((la, lb) => la.startsWith - lb.startsWith);
        return sorted.reduce((acc, layout, i, layouts) => {
            const next = layouts[i + 1];
            return [
                ...acc,
                {
                    layoutId: layout.id,
                    exemplary: layout.exemplary,
                    start: layout.startsWith,
                    end: next ? next.startsWith : Number.MAX_SAFE_INTEGER
                }
            ];
        }, []);
    }, [layouts]);
    const getCurrentLayout = (0, react_1.useCallback)((articleWidth) => {
        const range = layoutRanges.find(l => articleWidth >= l.start && articleWidth < l.end);
        return range;
    }, [layoutRanges]);
    const [layoutId, setLayoutId] = (0, react_1.useState)(undefined);
    const [deviation, setDeviation] = (0, react_1.useState)(1);
    (0, react_1.useEffect)(() => {
        if (!articleRectObserver)
            return;
        return articleRectObserver.on('resize', () => {
            const articleWidth = articleRectObserver.width;
            const { layoutId, exemplary } = getCurrentLayout(articleWidth);
            setLayoutId(layoutId);
            setDeviation(articleWidth / exemplary);
        });
    }, [articleRectObserver, getCurrentLayout]);
    return { layoutId, layoutDeviation: deviation };
};
exports.useCurrentLayout = useCurrentLayout;
