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

import type { Message } from "@/shared/types"
import { cacheCommands } from "./commands"
import { cacheApps } from "./webapp"
import { handleOutput } from "./scrollback"
import { handleStreamStart, handleStreamAppend, handleStreamReplace, handleStreamEnd } from "./stream"
import { handleGameStart } from "./game"
import { handleSessionStart, handleSessionUpdate } from "./session"

// message received from server
export async function dispatchMessage(msg: Message) {
  switch (msg.type) {
    case "output":
      handleOutput(msg); break
    case "commands":
      cacheCommands(msg.data); break
    case "apps":
      cacheApps(msg.data); break
    case "error":
      console.error(msg.data); break
    case "stream:start":
      handleStreamStart(msg); break
    case "stream:end":
      handleStreamEnd(msg); break
    case "stream:append":
      handleStreamAppend(msg); break
    case "stream:replace":
      handleStreamReplace(msg); break
    case "game:start":
      await handleGameStart(msg); break
    case "session:start":
      handleSessionStart(msg); break
    case "session:update":
      handleSessionUpdate(msg); break
    default:
      console.error("unknown message type", msg)
  }
}