import { Handlers } from "$fresh/server.ts";
import { MCProperties } from "../components/properties.tsx";
import {
  deserializeMCProperties,
  serializeMCProperties,
} from "../util/mcProperties.ts";

export const handler: Handlers = {
  async POST(req, ctx) {
    const filePath = `./server/server.properties`;
    const formData = await req.formData();
    const text = await Deno.readTextFile(filePath);
    const properties = deserializeMCProperties(text);

    for (const [key, value] of formData.entries()) {
      properties.set(key, value as string);
    }
    
    const serialized = serializeMCProperties(properties);

    await Deno.writeTextFile(filePath, serialized);
    
    return ctx.render();
  },
};

export default async function Properties() {
  const text = await Deno.readTextFile(`./server/server.properties`);
  const properties = await deserializeMCProperties(text);

  return <MCProperties properties={properties} />;
}
