// eslint-disable-next-line
importScripts('./files/pyodide.js')

function loadPyodideAndPackages() {
  // eslint-disable-next-line
  return loadPyodide({ indexURL: '/pyodide/files', checkAPIVersion: false })
}

const pyodideReadyPromise = loadPyodideAndPackages()

async function runLocal(pyodide, script, context) {
  await pyodide.loadPackagesFromImports(script)
  const locals = context ? pyodide.toPy(context) : undefined
  return pyodide.runPythonAsync(script, { locals })
}

async function runGlobal(pyodide, script, context) {
  await pyodide.loadPackagesFromImports(script)
  for (const key in context) {
    pyodide.globals.set(key, context[key])
  }
  const result = await pyodide.runPythonAsync(script)
  for (const key in context) {
    pyodide.globals.delete(key, context[key])
  }
  return result
}

onmessage = async (event) => {
  const pyodide = await pyodideReadyPromise
  const { id, script, context, global = false } = event.data
  try {
    const results = await (global ? runGlobal(pyodide, script, context) : runLocal(pyodide, script, context))
    postMessage({ results, id })
  } catch (error) {
    postMessage({ error: error.message || `${error}`, id })
  }
}
