////
// Dispatch client->server Messages received via WebSocket

import { basename } from "path"
import type { Message, InputMessage, SaveFileMessage } from "./shared/types"
import { runCommand } from "./shell"
import { send } from "./websocket"
import { setState } from "./state"

export async function dispatchMessage(ws: any, msg: Message) {
  // console.log("<- receive", msg)
  switch (msg.type) {
    case "input":
      await inputMessage(ws, msg); break

    case "save-file":
      await saveFileMessage(ws, msg); break

    case "session:update":
      for (const key of Object.keys(msg.data))
        setState(key, msg.data[key]);
      break

    default:
      send(ws, { type: "error", data: `unknown message: ${msg.type}` })
  }
}

async function inputMessage(ws: any, msg: InputMessage) {
  const result = await runCommand(msg.session, msg.id, msg.data as string, ws)

  if (typeof result.output === "object" && "game" in result.output) {
    send(ws, { id: msg.id, type: "game:start", data: result.output.game })
  } else {
    send(ws, { id: msg.id, type: "output", data: result })
  }
}

async function saveFileMessage(ws: any, msg: SaveFileMessage) {
  if (msg.id && typeof msg.data === "string") {
    await Bun.write(msg.id.replace("..", ""), msg.data, { createPath: true })
    send(ws, { type: "output", data: { status: "ok", output: `saved ${basename(msg.id)}` } })
  }
}

