// This Source Code Form is subject to the terms of the Mozilla Public
// License, v2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/
import * as Comlink from "comlink";
import { ComlinkWrap } from "@foxglove/den/worker";
import { ConfigStore } from "../utils/config-store";
function initWorker(callback) {
    const worker = new Worker(new URL("./deserialization.worker", import.meta.url), { type: "module", name: `message-decoder` });
    const { remote, dispose } = ComlinkWrap(worker);
    void remote.initCallback(Comlink.proxy(callback));
    return { remote, dispose };
}
const neuralCameraIntrinsics = JSON.parse(localStorage.getItem("neuralCameraIntrinsics") ?? "{}");
export function createMessageHandler(callback) {
    const workerPool = new Map();
    return {
        handle: (({ schema, buffer, topic }, errorCallback) => {
            let workerWrapper = workerPool.get(topic);
            if (!workerWrapper) {
                const newWorkerWrapper = initWorker(callback);
                workerWrapper = newWorkerWrapper;
                workerPool.set(topic, newWorkerWrapper);
            }
            const proxiedErrorCallback = errorCallback ? Comlink.proxy(errorCallback) : undefined;
            void workerWrapper.remote.handleMessageToDecode({ schema, buffer, topic, neuralCameraIntrinsics, stereoDepthMaxValue: Number(localStorage.getItem("stereoDepthMaxValue") ?? "8000") }, ConfigStore.getInstance(), proxiedErrorCallback);
        }),
        cleanup: () => {
            // Properly dispose of all workers and release Comlink proxies
            for (const workerWrapper of workerPool.values()) {
                workerWrapper.dispose();
            }
            workerPool.clear();
        },
    };
}
//# sourceMappingURL=message-handler.js.map