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) {
      console.log(JSON.stringify({ message: `Connection established`, remoteHost: ws.raw.remoteAddress }));

      chatRoom.addListener('message-added', function (e) {
        const message = JSON.stringify({
          message: e.message.message,
          chatter: e.message.chatter,
          timestamp: e.message.timestamp
        });

        ws.send(message);
      });
    },
    onMessage(event, ws) {
      const { data } = event;
      const message = JSON.parse(data);
      message.timestamp = Date.now() as string;

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


// 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),
  websocket
});

console.log(JSON.stringify({ message: `Chat is running`, port: process.env.APP_PORT}));
