import { Handlers } from "$fresh/server.ts";
import { SERVER_STATE } from "../../state/serverState.ts";
import { getActivePlayers } from "../../util/players.ts";

export const handler: Handlers = {
  GET(_req, _ctx) {
    let listener: (e: CustomEvent) => void;
    const body = new ReadableStream({
      async start(controller){
        if (SERVER_STATE.status !== 'running') return;
        const players = await getActivePlayers();

        const event = `event:players\ndata:${JSON.stringify(players)}\n\n`
        
        controller.enqueue(event);

        listener = async (e: CustomEvent<string>) => {
          if (e.detail.includes('joined the game') || e.detail.includes('lost connection')) {
            const players = await getActivePlayers();
            const event = `event: players\ndata: ${JSON.stringify(players)}\n\n`

            controller.enqueue(event);
          }
        }

        globalThis.addEventListener('stdoutmsg' as any, listener);
      },
      cancel() {
        globalThis.removeEventListener('stdoutmsg' as any, listener);
      }
    })

    return new Response(body.pipeThrough(new TextEncoderStream()), { headers: {
      "Content-Type": "text/event-stream",
      "cache-control": "no-cache"
    }}); 
  }
}