// This file should contain util functions for any web to start the GoldenViewer Emscripten module
// All this code is supposed to be needed prior to the Emscripten Module creation (ex. Module creation or SharedArrayBuffer support query or dynamic loading a javascript file)
// It should not contain development tools, only code that can be useful in production webs.

function supportSharedArrayBuffer() {
	// SharedArrayBuffer requires a secure context to be available
	// See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer#security_requirements
	return typeof SharedArrayBuffer !== "undefined";
}

function download(url) {
	return new Promise(function(resolve, reject) {
		var xhr = new XMLHttpRequest();
		xhr.open('GET', url, true);
		xhr.responseType = 'arraybuffer';
		xhr.onload = function() {
			if (xhr.status == 200)
				resolve(xhr.response);
			else
				reject();
		};
		xhr.onerror = function(e) { reject(e); };
		xhr.send(null);
	});
}

function loadJsFile(jsFile, onLoadCb = null) {
	const jsElm = document.createElement("script");
	jsElm.setAttribute("src", jsFile);
	jsElm.setAttribute("type", "text/javascript");
	jsElm.setAttribute("async", true);
	if (onLoadCb !== null) {
		jsElm.addEventListener("load", onLoadCb);
	}
	document.body.appendChild(jsElm);
}

function loadGoldenViewerJS(Module) {
	const scriptName = supportSharedArrayBuffer() ? "GoldenViewer.js" : "GoldenViewerNoThreads.js";
	return new Promise((resolve) => {
		// Download the .wasm file in parallel with the corresponding .js file
		const downloadPromise = download(scriptName.substring(0, scriptName.lastIndexOf(".")) + ".wasm");
		loadJsFile(scriptName, () => {
			downloadPromise.then((response) => {
				Module.wasmBinary = response;
				resolve(createModule(Module));
			});
		});
	});

	// INFO: this is how we should create the module if using -sEXPORT_ES6=1
	//const module = await import(script);
	//return module.default(Module);
}
