//==============================================================================
// The code below loads WebWorkers that were inserted using `ggp_template`.
// Autogenerated by ggp_template.py
//==============================================================================

/**
 *
 * @param {string} dep A script id OR a URL; if the id lookup fails, it assumes `dep` is a URL
 * @returns {string} The dependency `dep` as a URL
 */
function makeDependencyURL(dep) {
    if (self.document) {
        const elem = document.getElementById(dep);
        if (elem) return elem.src;
    } else if (self._LOADWORKER_INTERNALS) {
        const elem = _LOADWORKER_INTERNALS[dep];
        if (elem) return elem;
    }
    return dep;
}

const INTERNAL_DICT = "self._LOADWORKER_INTERNALS";

/**
 *
 * @param {string[]} dependencies A list of dependencies, in the order you want to import them
 * @returns {string} An `importScript` command that imports these dependencies
 */
function mkImportScripts(dependencies) {
    return "importScripts(" + dependencies.map(
        dependency => '"' + makeDependencyURL(dependency) + '"'
    ).join(",") + ");\n";
}

/**
 *
 * @param {string[]?} nestedDependencies A list of dependencies that should be made available to the internal WebWorker
 * @returns {string} Javascript code which, when executed, will store the dependencies in a variable
 */
function mkInternalDict(nestedDependencies) {
    if (!nestedDependencies || nestedDependencies.length === 0) return "";
    return `${INTERNAL_DICT} = {};` + nestedDependencies
        .map(dep => `${INTERNAL_DICT}["${dep}"] = "${makeDependencyURL(dep)}";`)
        .join("") + "\n";
}

/**
 * Create a WebWorker from a list of dependencies
 * @param {string} scriptId Either the id of a <script> tag or a URL
 * @param {string[]} dependencies A list of dependencies
 * @param {string[]?} nestedDependencies A list of nested dependencies if the worker wants to create its own workers
 *  (since workers cannot access top-level `script`'s)
 * @returns {Worker}
 */
function loadWorker(scriptId, dependencies, nestedDependencies) {
    const scriptContentURI = makeDependencyURL(scriptId);
    const scriptContent = mkImportScripts(dependencies) + mkInternalDict(nestedDependencies) +
         decodeURIComponent(scriptContentURI.split(",", 2)[1]);
    const blob = new Blob([scriptContent], { type: "text/javascript" });
    return new Worker(URL.createObjectURL(blob));
}
