/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/ban-ts-comment */
import { IoThread } from "./IoThread.js";
import { IoCommand, IoEvent, IoNotification } from "./PlatformBindings.js";

/**
 * Base class for ShareWorker threads.
 */
export class SharedWorkerThread extends IoThread {
  ports: MessagePort[] = [];

  async initialize(): Promise<void> {
    globalThis.addEventListener('connect', this.connectHandler.bind(this) as EventListener);
  }

  connectHandler(e: MessageEvent): void {
    const port = e.ports[0];
    this.ports.push(port);
    port.addEventListener('message', this.messageHandler.bind(this));
    port.start();
    port.postMessage('ready');
  }

  postMessage(message: IoNotification | IoEvent): void {
    this.ports.forEach(p => p.postMessage(message));
  }

  protected messageHandler(e: MessageEvent): void {
    if (e.data === 'init') {
      e.ports.forEach(p => p.postMessage('ready'));
      return;
    }
    const event = e.data as IoCommand | IoEvent;
    this.handleMessage(event);
  }
}
