import { WasmSharedTypedArray } from "./wasmSharedTypedArray";
import { WasmTypedArray } from "./wasmTypedArray";
const wasmInstanceMap = new WeakMap();
/**
 * Load MMD WASM instance
 *
 * Wasm instance type is determined by the argument instanceType
 *
 * For example, if you want to use most stable MMD WASM instance, pass MmdWasmDebugInstanceType to instanceType
 * @param instanceType MMD WASM instance type
 * @param threadCount Thread count for WASM threading (default: navigator.hardwareConcurrency). threadCount must be greater than 0
 * @returns MMD WASM instance
 */
export async function getMmdWasmInstance(instanceType, threadCount = navigator.hardwareConcurrency) {
    const wasmBindgen = instanceType.getWasmInstanceInner();
    {
        const instance = wasmInstanceMap.get(wasmBindgen);
        if (instance !== undefined)
            return instance;
    }
    let resolvePromise = null;
    wasmInstanceMap.set(wasmBindgen, new Promise(resolve => resolvePromise = resolve));
    const initOutput = await wasmBindgen.default();
    wasmBindgen.init();
    const memory = initOutput.memory;
    function createTypedArray(typedArrayConstructor, byteOffset, length) {
        return new WasmTypedArray(typedArrayConstructor, memory, byteOffset, length);
    }
    function createSharedTypedArray(typedArrayConstructor, byteOffset, length) {
        return new WasmSharedTypedArray(typedArrayConstructor, memory, byteOffset, length);
    }
    wasmBindgen.memory = memory;
    if (memory.buffer instanceof ArrayBuffer) {
        wasmBindgen.createTypedArray = createTypedArray;
    }
    else {
        wasmBindgen.createTypedArray = createSharedTypedArray;
    }
    await wasmBindgen.initThreadPool?.(threadCount);
    resolvePromise(wasmBindgen);
    return wasmBindgen;
}
