// Copyright 2025 The Lynx Authors. All rights reserved.
// Licensed under the Apache License Version 2.0 that can be found in the
// LICENSE file in the root directory of this source tree.
import { IndexMap } from '../../shared/index-map.js';
import { WorkletEvents } from '../../worklet-runtime/bindings/events.js';
import { registerDestroyTask } from '../runtime-destroy.js';
let resolveMap;
let cleanupReturnValueListener;
let unregisterReturnValueCleanup;
function initReturnValueListener() {
    const context = __JS__ ? lynx.getCoreContext() : lynx.getJSContext();
    resolveMap = new IndexMap();
    context.addEventListener(WorkletEvents.FunctionCallRet, onFunctionCallRet);
    cleanupReturnValueListener = () => {
        context.removeEventListener(WorkletEvents.FunctionCallRet, onFunctionCallRet);
        resolveMap = undefined;
        cleanupReturnValueListener = undefined;
    };
}
/**
 * @internal
 */
export function onFunctionCall(resolve) {
    ensureFunctionCallReturnCleanup();
    if (!resolveMap) {
        initReturnValueListener();
    }
    return resolveMap.add(resolve);
}
function ensureFunctionCallReturnCleanup() {
    if (unregisterReturnValueCleanup) {
        return;
    }
    unregisterReturnValueCleanup = registerDestroyTask(() => {
        resetFunctionCallReturnListener();
    });
}
export function resetFunctionCallReturnListener() {
    cleanupReturnValueListener?.();
    unregisterReturnValueCleanup?.();
    unregisterReturnValueCleanup = undefined;
}
export function dropFunctionCallReturnIds(resolveIds) {
    if (!resolveMap) {
        return;
    }
    for (const resolveId of resolveIds) {
        resolveMap.remove(resolveId);
    }
    if (resolveMap.size === 0) {
        resetFunctionCallReturnListener();
    }
}
function onFunctionCallRet(event) {
    const data = JSON.parse(event.data);
    const map = resolveMap;
    if (!map) {
        return;
    }
    const resolve = map.get(data.resolveId);
    if (!resolve) {
        return;
    }
    map.remove(data.resolveId);
    resolve(data.returnValue);
}
//# sourceMappingURL=return-value.js.map