////
// temporary hack for browser commands

import type { CommandOutput } from "../shared/types"
import { scrollback, content } from "./dom"
import { resize } from "./resize"
import { autoScroll } from "./scrollback"
import { sessionId } from "./session"
import { send } from "./websocket"
import { focusInput } from "./focus"

export const commands: string[] = []

export const browserCommands: Record<string, (...args: string[]) => void | Promise<void> | CommandOutput> = {
  "browser-session": () => sessionId,
  clear: () => scrollback.innerHTML = "",
  commands: () => {
    return { html: "<div>" + commands.map(cmd => `<a href="#help ${cmd}">${cmd}</a>`).join("") + "</div>" }
  },
  fullscreen: () => document.body.requestFullscreen(),
  mode: (mode?: string) => {
    if (!mode) {
      mode = document.body.dataset.mode === "tall" ? "cinema" : "tall"
      send({ type: "ui:mode", data: mode })
    }

    content.style.display = ""
    document.body.dataset.mode = mode
    resize()
    autoScroll()
    focusInput()
  },
  reload: () => window.location.reload(),
}

export function cacheCommands(cmds: string[]) {
  commands.length = 0
  commands.push(...cmds)
  commands.push(...Object.keys(browserCommands))
  commands.sort()
}