import { Handlers } from "$fresh/server.ts";
import { SERVER_STATE } from "../../../state/serverState.ts";
import { downloadFile } from "../../../util/download.ts";
import { getForgeDownload } from "../../../util/forge.ts";
import { getGameVersions } from "../../../util/gameVersions.ts";

export const handler: Handlers = {
  async GET(_req, _ctx) {
    const gameVersions = await getGameVersions();

    return new Response(JSON.stringify({
      gameVersions,
    }));
  },
  async POST(req, _ctx) {
    try {
      const data = await req.formData();

      // TODO: update for instances
      await downloadFile(
        await getForgeDownload(data.get("game") as string || "1.20.1"),
        "./server/installer.jar",
      );

      const installer = new Deno.Command("java", {
        args: [
          "-Xmx2G",
          "-jar",
          "./installer.jar",
          "--installServer",
        ],
        stderr: "piped",
        stdout: "piped",
        cwd: "./server",
      });

      // const process = installer.spawn();
      // process.stderr.pipeTo(Deno.stderr.writable);
      // process.stdout.pipeTo(Deno.stdout.writable);

      const { success } = await installer.output();

      if (!success) throw "failed to install forge server";

      const argFile = "./server/user_jvm_args.txt";
      const jvmArgs = await Deno.readTextFile(argFile);
      const memArgRx = /^(#\s)?(-Xmx)(.+)$/m;
      await Deno.writeTextFile(
        argFile,
        jvmArgs.replace(
          memArgRx,
          jvmArgs.match(memArgRx)?.at(0)?.replace(/#\s?/, "") || "-Xmx4G",
        ),
      );

      const runFiles = ["./server/run.sh", "./server/run.bat"];

      for (const runFile of runFiles) {
        const file = (await Deno.readTextFile(runFile))
          .replace("_args.txt", (e) => e + " nogui");

        await Deno.writeTextFile(runFile, file);
      }

      SERVER_STATE.serverType = "forge";

      await SERVER_STATE.startMCServer();

      const url = new URL(req.url);

      return Response.redirect(url.origin + "/setup/eula", 303);
      // return Response.redirect(url.origin + "/terminal", 303);
    } catch (e) {
      console.log(e);
      return new Response("Something bad happened", { status: 500 });
    }
  },
};
