/*
 * Application Insights JavaScript SDK - Core, 3.0.9
 * Copyright (c) Microsoft and contributors. All rights reserved.
 */


import { arrAppend, arrForEach, dumpObj } from "@nevware21/ts-utils";
import { _DYN_LENGTH } from "../__DynamicConstants";
import { _throwInternal } from "./DiagnosticLogger";
var _maxHooks;
var _hookAddMonitor;
/**
 * Test hook for setting the maximum number of unload hooks and calling a monitor function when the hooks are added or removed
 * This allows for automatic test failure when the maximum number of unload hooks is exceeded
 * @param maxHooks - The maximum number of unload hooks
 * @param addMonitor - The monitor function to call when hooks are added or removed
 */
export function _testHookMaxUnloadHooksCb(maxHooks, addMonitor) {
    _maxHooks = maxHooks;
    _hookAddMonitor = addMonitor;
}
/**
 * Create a IUnloadHookContainer which can be used to remember unload hook functions to be executed during the component unloading
 * process.
 * @returns A new IUnloadHookContainer instance
 */
export function createUnloadHookContainer() {
    var _hooks = [];
    function _doUnload(logger) {
        var oldHooks = _hooks;
        _hooks = [];
        // Remove all registered unload hooks
        arrForEach(oldHooks, function (fn) {
            // allow either rm or remove callback function
            try {
                (fn.rm || fn.remove).call(fn);
            }
            catch (e) {
                _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 73 /* _eInternalMessageId.PluginException */, "Unloading:" + dumpObj(e));
            }
        });
        if (_maxHooks && oldHooks[_DYN_LENGTH /* @min:%2elength */] > _maxHooks) {
            _hookAddMonitor ? _hookAddMonitor("doUnload", oldHooks) : _throwInternal(null, 1 /* eLoggingSeverity.CRITICAL */, 48 /* _eInternalMessageId.MaxUnloadHookExceeded */, "Max unload hooks exceeded. An excessive number of unload hooks has been detected.");
        }
    }
    function _addHook(hooks) {
        if (hooks) {
            arrAppend(_hooks, hooks);
            if (_maxHooks && _hooks[_DYN_LENGTH /* @min:%2elength */] > _maxHooks) {
                _hookAddMonitor ? _hookAddMonitor("Add", _hooks) : _throwInternal(null, 1 /* eLoggingSeverity.CRITICAL */, 48 /* _eInternalMessageId.MaxUnloadHookExceeded */, "Max unload hooks exceeded. An excessive number of unload hooks has been detected.");
            }
        }
    }
    return {
        run: _doUnload,
        add: _addHook
    };
}
//# sourceMappingURL=UnloadHookContainer.js.map