"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ReactRenderHook = void 0;
const tslib_1 = require("tslib");
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = tslib_1.__importDefault(require("react"));
const Scheduler_1 = require("@appglue/common/dist/Common/Scheduler");
const DataUtilities_1 = require("@appglue/common/dist/Common/DataUtilities");
const Log_1 = require("@appglue/common/dist/Log");
const LogLevel_1 = require("@appglue/common/dist/Plugins/Logging/LogLevel");
// this is a small class that is inserted into the rendering cycle so that we can see when mounting and updating happen.
// after callback is made, it unregistrs.
class ReactRenderHook extends react_1.default.Component {
    static callbacks = [];
    static hooks = {};
    static waitingForRender = false;
    hookIsMounted = false;
    id = DataUtilities_1.DataUtilities.generateUniqueId();
    static registerCallback(name, callback) {
        this.waitingForRender = true;
        let needsCleanup = false;
        // we force update on all the render hooks.  When this is done, it will allow us to know when we re render.
        for (let i of Object.values(this.hooks)) {
            try {
                if (!i)
                    needsCleanup = true;
                if (i && i.hookIsMounted)
                    i.forceUpdate();
            }
            catch (e) {
                (0, Log_1.log)("Mapping", LogLevel_1.LogLevel.ERROR, "error in force update", e);
            }
        }
        // rebuild hook list to get rid of undefined.
        if (needsCleanup) {
            let values = { ...this.hooks };
            this.hooks = {};
            for (let key in values) {
                let val = values[key];
                if (val)
                    this.hooks[key] = val;
            }
        }
        Scheduler_1.Scheduler.getScheduler("react-render-callback", 30).addToSchedule(name, callback, false, () => {
            return ReactRenderHook.waitingForRender === true;
        });
        Scheduler_1.Scheduler.getScheduler("react-render-callback", 30).addToPostSchedule(name, callback, false, () => {
            return ReactRenderHook.waitingForRender === true;
        });
    }
    componentDidMount() {
        ReactRenderHook.hooks[this.id] = this;
        ReactRenderHook.waitingForRender = false;
        this.hookIsMounted = true;
    }
    componentDidUpdate() {
        ReactRenderHook.hooks[this.id] = this;
        ReactRenderHook.waitingForRender = false;
        this.hookIsMounted = true;
    }
    componentWillUnmount() {
        // making this undefined registers it for cleanup.
        ReactRenderHook.hooks[this.id] = undefined;
        this.hookIsMounted = false;
    }
    render() {
        return (0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, {});
    }
}
exports.ReactRenderHook = ReactRenderHook;
//# sourceMappingURL=ReactRenderHook.js.map