import { Method } from './const'
import { WidgetGeoJsonSourceImpl } from './widget-geojson-source-impl'
import type { WorkerRequest, WorkerResponse } from './types'
import type { WidgetGeoJsonSourceProps } from './widget-geojson-source'

/*
 * Web Worker.
 *
 * Workers are scoped to the lifecycle of a single WidgetGeoJsonSource instance,
 * representing and executing calculations on a single datasource.
 */

let source: WidgetGeoJsonSourceImpl

addEventListener('message', (e) => {
  const { method, params, requestId } = e.data as WorkerRequest

  if (method === Method.INIT) {
    source = new WidgetGeoJsonSourceImpl({
      ...(params[0] as WidgetGeoJsonSourceProps),
      widgetWorker: false,
    })
    return
  }

  if (!source) {
    const error = `Cannot execute "${method}" on uninitialized source.`
    postMessage({ ok: false, error, requestId } as WorkerResponse)
    return
  }

  // @ts-expect-error No type-checking dynamic method name.
  Promise.resolve(source[method](...params))
    .then((result) => {
      postMessage({ ok: true, result, requestId } as WorkerResponse)
    })
    .catch((error) => {
      // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
      postMessage({ ok: false, error, requestId } as WorkerResponse)
    })
})
