import { onDestroy } from "../../lib/skeleton/index.js";
import module from "./lib/tiff_wasm.js";

export default async function(IImage) {
    const worker = new Worker(
        new URL("./loader_tiff.worker.js", import.meta.url),
        { type: "module" },
    );
    await new Promise((resolve) => worker.addEventListener(
        "message", resolve, { once: true },
    ));
    onDestroy(() => worker.terminate());

    return class Impl extends IImage {
        constructor() {
            super();
        }

        getSRC(response) {
            return new Promise((resolve, reject) => {
                worker.onerror = (err) => {
                    reject(err);
                };
                worker.onmessage = (event) => {
                    const url = URL.createObjectURL(new Blob(
                        [ event.data.response ],
                        { type: "image/jpeg" },
                    ));
                    onDestroy(() => URL.revokeObjectURL(url));
                    resolve(url);
                };
                worker.postMessage({ response }, [ response ]);
            });
        }
    }
}
