/**
 *@returns {void}
 */
export function _PdfOpenJpegRunner() {
    var baseUrl = '';
    var moduleLoaded = false;
    var moduleString = 'Module';
    var pdfiumWindow = {}; //eslint-disable-line
    var OpenJpegModule = pdfiumWindow[moduleString] || {}; //eslint-disable-line
    var ctx = self; //eslint-disable-line
    /**
     *@returns {void}
     */
    function postLoaded() {
        ctx.postMessage({ message: 'loaded' });
    }
    /**
     *@returns {void}
     */
    function checkIfEverythingWasLoaded() {
        if (moduleLoaded) {
            postLoaded();
        }
    }
    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(/\/+$/, '');
                importScripts(baseUrl + "/openjpeg.js");
                OpenJpegModule.url = baseUrl;
                OpenJpegModule.onRuntimeInitialized = function () {
                    moduleLoaded = true;
                    checkIfEverythingWasLoaded();
                };
                self['OpenJpegModule'](OpenJpegModule); //eslint-disable-line
                break;
            case 'decodeJPX':
                {
                    if (!moduleLoaded) {
                        ctx.postMessage({ message: 'decodeError', error: 'Module not loaded yet.' });
                        return;
                    }
                    var bytes = data.url; //eslint-disable-line
                    var mod = OpenJpegModule; //eslint-disable-line
                    var u8 = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
                    var ptr = 0;
                    try {
                        ptr = mod._malloc(u8.length);
                        if (mod.writeArrayToMemory) {
                            mod.writeArrayToMemory(u8, ptr);
                        }
                        else {
                            mod.HEAPU8.set(u8, ptr);
                        }
                        var ok = mod._jp2_decode(ptr, u8.length) | 0;
                        ctx.postMessage({ message: mod.imageData, success: ok === 1 });
                    }
                    catch (ex) {
                        ctx.postMessage({ message: 'decodeError', error: ex.message });
                    }
                }
                break;
            case 'getModule':
                ctx.postMessage({ message: 'moduleInfo', id: data.id, loaded: moduleLoaded });
                break;
            case 'unloadOpenJpeg':
                ctx.postMessage({ message: 'unloaded' });
                break;
        }
    };
}
