////
// Terminal input is handled by a <textarea> and friends.

import { cmdInput, cmdLine } from "./dom"
import { runCommand } from "./shell"
import { resetHistory } from "./history"

export function initInput() {
    cmdInput.addEventListener("keydown", inputHandler)
    cmdInput.addEventListener("paste", pasteHandler)
}

async function inputHandler(event: KeyboardEvent) {
    const target = event.target as HTMLElement
    if (target?.id !== cmdInput.id) return

    if (event.key === "Escape" || (event.ctrlKey && event.key === "c")) {
        clearInput()
        resetHistory()
    } else if (event.key === "Tab") {
        event.preventDefault()
    } else if (event.shiftKey && event.key === "Enter") {
        cmdInput.rows += 1
        cmdLine.dataset.extended = "true"
    } else if (event.key === "Enter") {
        event.preventDefault()
        await runCommand(cmdInput.value)
        clearInput()
    }

    // cleanup
    setTimeout(() => {
        if (cmdLine.dataset.extended && !cmdInput.value.includes("\n")) {
            cmdInput.rows = 1
            cmdInput.style.height = "auto"
            delete cmdLine.dataset.extended
        }
    }, 0)
}

function pasteHandler(event: ClipboardEvent) {
    const text = event.clipboardData?.getData("text") || ""

    if (!text.includes("\n")) {
        delete cmdLine.dataset.extended
        return
    }

    setTimeout(() => {
        cmdInput.style.height = "auto"
        cmdInput.style.height = cmdInput.scrollHeight + "px"
        cmdLine.dataset.extended = "true"
    }, 0)
}

function clearInput() {
    cmdInput.value = ""
    cmdInput.rows = 1
    cmdInput.style.height = "auto"
    delete cmdLine.dataset.extended
}