// Web Worker for <layout-foundry-quantities>. Runs the tile, flooring, paving, wallpaper, paint, decking,
// fencing, gravel and turf planners.
// Measurements stay in this worker's memory. Nothing is sent anywhere.
// The result is written in the language the element asks for, with the words it sends; English is built in.

import { computeQuantity } from "./quantities-core";
import { CoreText, ENGLISH_CORE } from "./quantities-text";
import type { QuantityRequest, QuantityResponse } from "./worker-protocol";

interface WorkerScope {
  onmessage: ((event: MessageEvent<QuantityRequest>) => void) | null;
  postMessage(message: QuantityResponse): void;
}
const scope = self as unknown as WorkerScope;

// The last language asked for, kept so its words are prepared once.
let text: CoreText = ENGLISH_CORE;

scope.onmessage = ({ data }) => {
  if (!data.lang || !data.messages) text = ENGLISH_CORE;
  else if (data.lang !== text.lang) text = new CoreText(data.lang, data.messages);
  try {
    scope.postMessage({ type: "quantity", requestId: data.requestId, result: computeQuantity(data.config, data.inputs, text) });
  } catch (error) {
    scope.postMessage({ type: "error", requestId: data.requestId, message: text.shared((error as Error).message) });
  }
};
scope.postMessage({ type: "ready", requestId: 0 });
