/// <reference lib="webworker" />
import {
  JavaEngineAdapter,
  JAVA_ENGINE_VERSION,
} from "../regex/execution/adapters/java/JavaEngineAdapter";
import { importJavaRegexModule } from "../regex/execution/adapters/java/java-module";
import {
  WORKER_PROTOCOL_VERSION,
  workerError,
  type EngineWorkerOperation,
  type EngineWorkerResult,
  type WorkerRequest,
  type WorkerResponse,
} from "../regex/execution/worker-protocol";

const scope = self as DedicatedWorkerGlobalScope;
let adapterPromise: Promise<JavaEngineAdapter> | undefined;

function applicationRoot(): URL {
  const worker = new URL(scope.location.href);
  const assets = worker.pathname.lastIndexOf("/assets/");
  if (assets >= 0) {
    worker.pathname = worker.pathname.slice(0, assets + 1);
  } else {
    const sourceWorker = worker.pathname.lastIndexOf("/src/workers/");
    worker.pathname =
      sourceWorker >= 0 ? worker.pathname.slice(0, sourceWorker + 1) : "/";
  }
  worker.search = "";
  worker.hash = "";
  return worker;
}

async function loadAdapter(): Promise<JavaEngineAdapter> {
  const moduleUrl = new URL("engines/java/java-regex.mjs", applicationRoot());
  const module = await importJavaRegexModule(moduleUrl);
  const adapter = new JavaEngineAdapter(
    module,
    `TeaVM JavaScript · ${scope.navigator.userAgent} · not OpenJDK`,
  );
  const info = await adapter.load();
  if (info.engineVersion !== JAVA_ENGINE_VERSION) {
    throw new Error("Loaded TeaVM Java runtime identity does not match.");
  }
  return adapter;
}

scope.onmessage = async (
  event: MessageEvent<WorkerRequest<EngineWorkerOperation>>,
) => {
  const request = event.data;
  if (request.protocolVersion !== WORKER_PROTOCOL_VERSION) return;
  let response: WorkerResponse<EngineWorkerResult>;
  try {
    adapterPromise ??= loadAdapter();
    const adapter = await adapterPromise;
    let payload: EngineWorkerResult;
    if (request.payload.kind === "load") {
      payload = { kind: "load", info: await adapter.load() };
    } else if (request.payload.kind === "execute") {
      payload = {
        kind: "execute",
        result: await adapter.execute(request.payload.request),
      };
    } else {
      payload = {
        kind: "replace",
        result: await adapter.replace(request.payload.request),
      };
    }
    response = {
      protocolVersion: WORKER_PROTOCOL_VERSION,
      requestId: request.requestId,
      generation: request.generation,
      ok: true,
      payload,
    };
  } catch (error) {
    response = {
      protocolVersion: WORKER_PROTOCOL_VERSION,
      requestId: request.requestId,
      generation: request.generation,
      ok: false,
      error: workerError(error),
    };
  }
  scope.postMessage(response);
};
