////
// The shell runs on the server and processes input, returning output.

import { addInput, setStatus, addOutput } from "./scrollback"
import { send } from "./websocket"
import { randomId } from "../shared/utils"
import { addToHistory } from "./history"
import { browserCommands } from "./commands"

export async function runCommand(input: string) {
    if (!input.trim()) return

    if (input.includes(";")) {
        input.split(";").forEach(async cmd => await runCommand(cmd.trim()))
        return
    }

    const id = randomId()

    addToHistory(input)
    addInput(id, input)

    const [cmd = "", ...args] = input.split(" ")

    if (browserCommands[cmd]) {
        const result = await browserCommands[cmd](...args)
        if (result) addOutput(id, result)
        setStatus(id, "ok")
    } else {
        send({ id, type: "input", data: input })
    }
}

