/**
 *@returns {void}
 */
export function _PdfQcmsRunner() {
    var baseUrl = '';
    var moduleLoaded = false;
    var _memoryArray;
    var _mustAddAlpha = false;
    var _destBuffer = null; // eslint-disable-line
    var _destOffset = 0;
    var ctx = self; // eslint-disable-line
    var qcmsModule = {}; // eslint-disable-line
    var lastResult = null;
    var nextTransformerId = 1;
    var transformerMap = new Map();
    /**
     *@returns {void}
     */
    function postLoaded() {
        ctx.postMessage({ message: 'loaded' });
    }
    /**
     *@returns {void}
     */
    function checkIfEverythingWasLoaded() {
        if (moduleLoaded) {
            postLoaded();
        }
    }
    /**
     * Attaches helper functions to the given module.
     *
     * @param {any} mod - The module object to which helpers will be attached.
     * @returns {void}
     */
    function attachHelpersToModule(mod) {
        mod.copy_result = function (ptr, len) {
            _memoryArray = new Uint8Array(qcmsModule.memory.buffer);
            if (_mustAddAlpha) {
                for (var i = ptr, ii = ptr + len, j = _destOffset; i < ii; i += 3, j += 4) {
                    _destBuffer[j] = _memoryArray[i];
                    _destBuffer[j + 1] = _memoryArray[i + 1];
                    _destBuffer[j + 2] = _memoryArray[i + 2];
                    _destBuffer[j + 3] = 255;
                }
            }
            else {
                for (var i = ptr, ii = ptr + len, j = _destOffset; i < ii; i += 3, j += 4) {
                    _destBuffer[j] = _memoryArray[i];
                    _destBuffer[j + 1] = _memoryArray[i + 1];
                    _destBuffer[j + 2] = _memoryArray[i + 2];
                }
            }
        };
        mod.copy_rgb = function (ptr) {
            _memoryArray = new Uint8Array(qcmsModule.memory.buffer);
            _destBuffer[_destOffset] = _memoryArray[ptr];
            _destBuffer[_destOffset + 1] = _memoryArray[ptr + 1];
            _destBuffer[_destOffset + 2] = _memoryArray[ptr + 2];
        };
        mod.make_cssRGB = function (_r, _g, _b) {
            _memoryArray = new Uint8Array(qcmsModule.memory.buffer);
        };
    }
    /**
     *@returns {void}
     */
    function ensureLoaded() {
        if (!moduleLoaded) {
            throw new Error('Module not loaded yet.');
        }
    }
    ctx.onmessage = function (event) {
        var data = event.data; // eslint-disable-line
        if (!data || !data.message) {
            return;
        }
        switch (data.message) {
            case 'initialLoading': {
                baseUrl = (data.url || '').replace(/\/+$/, '');
                try {
                    importScripts(baseUrl + "/qcms.js");
                }
                catch (e) {
                    ctx.postMessage({ message: 'initError', error: "Failed to import qcms.js: " + (e.message || e), reqId: data.reqId });
                    return;
                }
                try {
                    attachHelpersToModule(qcmsModule);
                    qcmsModule.url = baseUrl;
                    qcmsModule.onRuntimeInitialized = function () {
                        moduleLoaded = true;
                        checkIfEverythingWasLoaded();
                    };
                    var factory = self['qcmsModule']; // eslint-disable-line
                    if (typeof factory !== 'function') {
                        ctx.postMessage({ message: 'initError', error: 'qcmsModule factory not found after loading qcms.js', reqId: data.reqId });
                        return;
                    }
                    factory(qcmsModule);
                }
                catch (e) {
                    ctx.postMessage({ message: 'initError', error: e.message || String(e), reqId: data.reqId });
                }
                break;
            }
            case 'getModule': {
                ctx.postMessage({ message: 'moduleInfo', id: data.id, loaded: moduleLoaded, reqId: data.reqId });
                break;
            }
            case 'convertQcms': {
                try {
                    ensureLoaded();
                    var _a = data.payload, src = _a.src, profileBytes = _a.profileBytes, inType = _a.inType, intent = _a.intent;
                    lastResult = null;
                    var u8Src = src instanceof Uint8Array ? src : new Uint8Array(src);
                    var u8Profile = profileBytes instanceof Uint8Array ? profileBytes : new Uint8Array(profileBytes);
                    var mod = qcmsModule; // eslint-disable-line
                    var transformer = mod.qcms_transformer_from_memory(u8Profile, inType >>> 0, intent >>> 0) >>> 0;
                    mod.qcms_convert_array(transformer, u8Src);
                    mod.qcms_drop_transformer(transformer);
                    if (!lastResult) {
                        ctx.postMessage({
                            message: 'convertError',
                            error: 'QCMS conversion finished but no result was captured. Ensure qcms.js calls Module.copy_result(ptr, len) and exposes Module.HEAPU8.',
                            reqId: data.reqId
                        });
                        return;
                    }
                    ctx.postMessage({ message: 'convertResult', data: lastResult, reqId: data.reqId }, [lastResult.buffer]);
                }
                catch (ex) {
                    ctx.postMessage({ message: 'convertError', error: ex.message || String(ex), reqId: data.reqId });
                }
                break;
            }
            case 'createTransformer': {
                try {
                    ensureLoaded();
                    var _c = data.payload, profileBytes = _c.profileBytes, inType = _c.inType, intent = _c.intent;
                    var u8Profile = profileBytes instanceof Uint8Array ? profileBytes : new Uint8Array(profileBytes);
                    var mod = qcmsModule; // eslint-disable-line
                    var handle = mod.qcms_transformer_from_memory(u8Profile, inType >>> 0, intent >>> 0) >>> 0;
                    if (!handle) {
                        ctx.postMessage({ message: 'createTransformerError', error: 'Failed to create transformer', reqId: data.reqId });
                        return;
                    }
                    var id = nextTransformerId++;
                    transformerMap.set(id, handle);
                    ctx.postMessage({ message: 'transformerCreated', id: id, handle: handle, reqId: data.reqId });
                }
                catch (ex) {
                    ctx.postMessage({ message: 'createTransformerError', error: ex.message || String(ex), reqId: data.reqId });
                }
                break;
            }
            case 'convertWith': {
                try {
                    var _d = data.payload, id = _d.id, src = _d.src, dest = _d.dest, destOffset = _d.destOffset, alpha = _d.alpha;
                    _mustAddAlpha = alpha && dest.buffer === src.buffer;
                    _destBuffer = dest;
                    _destOffset = destOffset;
                    lastResult = null;
                    var u8Src = src instanceof Uint8Array ? src : new Uint8Array(src);
                    var mod = qcmsModule; // eslint-disable-line
                    mod.qcms_convert_array(id, u8Src);
                    _mustAddAlpha = false;
                    _destBuffer = null;
                    ctx.postMessage({ message: 'convertWithResult', id: id, data: dest, reqId: data.reqId });
                }
                catch (ex) {
                    ctx.postMessage({ message: 'convertWithError', error: ex.message || String(ex), reqId: data.reqId });
                }
                break;
            }
            case 'convertOne': {
                try {
                    ensureLoaded();
                    var _e = data.payload, id = _e.id, dest = _e.dest, destOffset = _e.destOffset, value = _e.value, css = _e.css;
                    lastResult = null;
                    var mod = qcmsModule; // eslint-disable-line
                    _destBuffer = dest;
                    _destOffset = destOffset;
                    mod.qcms_convert_one(id, value, !!css);
                    _destBuffer = new Uint8Array([]);
                    ctx.postMessage({ message: 'convertOneResult', id: id, data: lastResult, reqId: data.reqId });
                }
                catch (ex) {
                    ctx.postMessage({ message: 'convertOneError', error: ex.message || String(ex), reqId: data.reqId });
                }
                break;
            }
            case 'convertThree': {
                try {
                    ensureLoaded();
                    var _f = data.payload, id = _f.id, dest = _f.dest, destOffset = _f.destOffset, r = _f.r, g = _f.g, b = _f.b, css = _f.css;
                    lastResult = null;
                    var mod = qcmsModule; // eslint-disable-line
                    _destBuffer = dest;
                    _destOffset = destOffset;
                    mod.qcms_convert_three(id, r, g, b, !!css);
                    _destBuffer = new Uint8Array([]);
                    ctx.postMessage({ message: 'convertThreeResult', id: id, data: lastResult, reqId: data.reqId });
                }
                catch (ex) {
                    ctx.postMessage({ message: 'convertThreeError', error: ex.message || String(ex), reqId: data.reqId });
                }
                break;
            }
            case 'convertFour': {
                try {
                    ensureLoaded();
                    var _h = data.payload, id = _h.id, dest = _h.dest, destOffset = _h.destOffset, c = _h.c, m = _h.m, y = _h.y, k = _h.k, css = _h.css;
                    lastResult = null;
                    var mod = qcmsModule; // eslint-disable-line
                    _destBuffer = dest;
                    _destOffset = destOffset;
                    mod.qcms_convert_four(id, c, m, y, k, false);
                    _destBuffer = new Uint8Array([]);
                    ctx.postMessage({ message: 'convertFourResult', id: id, data: lastResult, reqId: data.reqId });
                }
                catch (ex) {
                    ctx.postMessage({ message: 'convertFourError', error: ex.message || String(ex), reqId: data.reqId });
                }
                break;
            }
            case 'dropTransformer': {
                try {
                    ensureLoaded();
                    var id = data.payload.id;
                    var handle = transformerMap.get(id);
                    if (handle) {
                        transformerMap.delete(id);
                        var mod = qcmsModule; // eslint-disable-line
                        try {
                            mod.qcms_drop_transformer(handle);
                        }
                        catch (_j) {
                            ctx.postMessage({ message: 'transformerDroppedError', id: id, reqId: data.reqId });
                        }
                    }
                    ctx.postMessage({ message: 'transformerDropped', id: id, reqId: data.reqId });
                }
                catch (ex) {
                    ctx.postMessage({ message: 'dropTransformerError', error: ex.message || String(ex), reqId: data.reqId });
                }
                break;
            }
            case 'unloadQcms': {
                try {
                    var mod_1 = qcmsModule; // eslint-disable-line
                    transformerMap.forEach(function (handle) {
                        try {
                            mod_1.qcms_drop_transformer(handle);
                        }
                        catch (_a) {
                            ctx.postMessage({ message: 'unloadedQcmsError', reqId: data.reqId });
                        }
                    });
                }
                catch (_k) {
                    ctx.postMessage({ message: 'unloadedError', reqId: data.reqId });
                }
                transformerMap.clear();
                ctx.postMessage({ message: 'unloaded', reqId: data.reqId });
                break;
            }
        }
    };
}
