import { Hono } from "hono";
import { serveStatic, createBunWebSocket } from "hono/bun";
import type { ServerWebSocket } from "hono";
import {
  chatRoom,
  createMessageString,
  type Message
} from "./chat-room.ts";

const app = new Hono();

// Set up the chat socket
const { upgradeWebSocket, websocket } = createBunWebSocket<ServerWebSocket>();
app.get("/chat-service", upgradeWebSocket((c) => {
  return {
    onOpen(event, ws) {
      chatRoom.addListener('message-added', function (e) {
        ws.send(JSON.stringify({
          message: e.message.message,
          chatter: e.message.chatter,
          timestamp: e.message.timestamp
        }));
      });
    },
    onMessage(event, ws) {
      const { data } = event;
      const message = JSON.parse(data);
      message.timestamp = Date.now() as string;

      chatRoom.addMessage(message);
    },
    onClose() {
      console.log("Connection closed.");
    },
    onError(event, ws) {
      console.error(event);
      ws.close();
    }
  }
}));

// set up the username, somehow
// set the session for a user
app.post("/login", async (c) => {
  const user = await c.req.parseBody();
  let success: boolean = false;

  if (!users.find((u) => u == user.username)) {
    users.push(user.username);
    success = true;
  }

  return c.json({ success });
});

// get the HTML and JS from the static repo
app.use("/", serveStatic({ path: "/static/index.html" }));
app.use("/*", serveStatic({ root: "/static" }));

Bun.serve({
  fetch: app.fetch,
  port: parseInt(process.env.APP_PORT as string) || 3000,
  websocket
});
