////
// Command input history storage and navigation.

import { cmdInput, cmdLine } from "./dom"

const history: string[] = ["one", "two", "three"]
let idx = -1
let savedInput = ""

export function initHistory() {
  cmdInput.addEventListener("keydown", navigateHistory)
}

export function addToHistory(input: string) {
  if (history.length === 0 || history[0] === input)
    return

  history.unshift(input)
  resetHistory()
}

export function resetHistory() {
  idx = -1
  savedInput = ""
}

function navigateHistory(e: KeyboardEvent) {
  if (cmdLine.dataset.extended) return

  if (e.key === "ArrowUp" || (e.ctrlKey && e.key === "p")) {
    e.preventDefault()
    if (idx >= history.length - 1) return

    if (idx === -1)
      savedInput = cmdInput.value

    cmdInput.value = history[++idx] || ""

    if (idx >= history.length) idx = history.length - 1
  } else if (e.key === "ArrowDown" || (e.ctrlKey && e.key === "n")) {
    e.preventDefault()

    if (idx <= 0) {
      cmdInput.value = savedInput
      idx = -1
      return
    }

    cmdInput.value = history[--idx] || ""

    if (idx < -1) idx = -1
  } else if (idx !== -1) {
    resetHistory()
  }
}