"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useStacking = void 0;
const tslib_1 = require("tslib");
const React = tslib_1.__importStar(require("react"));
const uuid_1 = require("../utils/uuid");
const setZIndexMap = {};
const zIndexMap = [];
const BASE_Z_INDEX = 1000;
/**
 * Used to facilitate the stacking between multiple opened windows.
 * When calling 'bringToFront' brings caller to top.
 * This is done by changing the zIndex of all registered window-modals.
 */
const useStacking = () => {
    const modalZIndexId = React.useMemo(() => (0, uuid_1.createUuid)(), []);
    const [zIndex, setZIndex] = React.useState(BASE_Z_INDEX);
    React.useEffect(() => {
        setZIndexMap[modalZIndexId] = setZIndex;
        return () => {
            // clean-up
            delete setZIndexMap[modalZIndexId];
            const indexInMap = zIndexMap.indexOf(modalZIndexId);
            zIndexMap.splice(indexInMap, 1);
        };
    }, [modalZIndexId]);
    const bringInFront = React.useCallback(() => {
        if (zIndexMap.includes(modalZIndexId)) {
            const indexInMap = zIndexMap.indexOf(modalZIndexId);
            zIndexMap.splice(indexInMap, 1);
            zIndexMap.push(modalZIndexId);
        }
        else {
            zIndexMap.push(modalZIndexId);
        }
        zIndexMap.forEach((id, index) => {
            setZIndexMap?.[id]?.(BASE_Z_INDEX + index * 10);
        });
    }, []);
    return {
        zIndex,
        bringInFront,
    };
};
exports.useStacking = useStacking;
