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

export enum ManageAction {
  start = "start",
  stop = "stop",
  restart = "restart",
  kill="kill"
}

export const handler: Handlers = {
  async POST(req) {
    const body: ManageAction & string = await req.text() as ManageAction;
    switch (body) {
      case ManageAction.start:
        SERVER_STATE.startMCServer();
        return new Response("started");
      case ManageAction.stop:
        SERVER_STATE.gracefullyStopMCServer();
        return new Response("stopped");
      case ManageAction.kill:
        SERVER_STATE.forceStopMCServer();
        return new Response("stopped");
      case ManageAction.restart:
        SERVER_STATE.restartMCServer();
        return new Response("restarted");
      default:
        SERVER_STATE.sendStdIn(body);
        return new Response("action done");
    }
  },
  GET(_req, _ctx) {
    let listener: (e: CustomEvent) => void;
    const body = new ReadableStream({
      async start(controller){
        const event = `event: status\ndata: ${SERVER_STATE.status}\n\n`
        controller.enqueue(event);
        listener = (e) => {
          const event = `event: status\ndata: ${e.detail}\n\n`
          controller.enqueue(event);
        };
        globalThis.addEventListener('serverstatuschange' as any, listener)
      },
      cancel() {
        globalThis.removeEventListener('serverstatuschange' as any, listener);
      }
    })

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