import LibRaw from "./lib/raw_wasm.js";

let raw;
let ready = (async () => {
	const module = await LibRaw();
	raw = new module.LibRaw();
})();

self.onmessage = async (event) => {
    const { fn, args } = event.data;
    try {
	    await ready;
        let out = postProcess(fn, raw[fn](...args));
        const transfer = [];
        if (out?.buffer instanceof Uint8Array) transfer.push(out.buffer);
        self.postMessage(
            { resolve: out },
            transfer,
        );
    } catch (err) {
        self.postMessage({ reject: err });
    }
};

function postProcess(fn, result) {
    switch (fn) {
    case "imageData":
        const { mime, data, preview } = result;
        switch (mime) {
        case "image/jpeg":
            return { buffer: data.buffer, type: "image/jpeg", preview };
        case "image/bmp":
            return { buffer: data.buffer, type: "image/bmp", preview };
        default:
            throw new Error(`Unsupported mime=${mime}`);
        }
    default:
        return result;
    }
}
