////
// Blinking c64 cursor

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

const cursor = "Û"
let cmdCursor: HTMLTextAreaElement
let enabled = true

export function initCursor() {
    cmdCursor = $("command-cursor") as HTMLTextAreaElement
    cmdInput.addEventListener("keydown", showCursor)
    document.addEventListener("focus", cursorEnablerHandler, true)
    showCursor()
}

function showCursor(e: KeyboardEvent | any = {}) {
    if (!enabled) {
        cmdCursor.value = ""
        return
    }

    if (e.key === "Enter" && !e.shiftKey) {
        cmdCursor.value = cursor
        return
    }

    requestAnimationFrame(() =>
        cmdCursor.value = buildBlankCursorLine() + cursor
    )
}

function cursorEnablerHandler(e: Event) {
    if (!e.target) return
    const target = e.target as HTMLElement

    enabled = target.id === "command-textbox"
    showCursor()
}

function buildBlankCursorLine(): string {
    let line = ""
    for (const char of cmdInput.value.slice(0, cmdInput.selectionEnd)) {
        line += char === "\n" ? char : " "
    }
    return line
}