////
// All forms are submitted via ajax.

import type { CommandResult, CommandOutput } from "../shared/types"
import { sessionId } from "./session"
import { setStatus, replaceOutput } from "./scrollback"
import { focusInput } from "./focus"

export function initForm() {
  document.addEventListener("submit", submitHandler)
}

export const submitHandler = async (e: SubmitEvent) => {
  e.preventDefault()

  const form = e.target
  if (!(form instanceof HTMLFormElement)) return

  const li = form.closest(".output")
  if (!(li instanceof HTMLLIElement)) return

  const id = li.dataset.id
  if (!id) return

  let output: CommandOutput
  let error = false

  try {
    const fd = new FormData(form)

    const data: CommandResult = await fetch("/cmd" + new URL(form.action).pathname, {
      method: "POST",
      headers: { "X-Session": sessionId }, // don't set Content-Type manually
      body: fd
    }).then(r => r.json())

    output = data.output
    error = data.status === "error"
  } catch (e: any) {
    output = e.message || e.toString()
    error = true
  }

  if (error) setStatus(id, "error")

  replaceOutput(id, output)
  focusInput()
}
