export default class Input {
    constructor(commandHandler, outputHandler) {
        this.handler = commandHandler;
        this.output = outputHandler;
        this.echoInput = true;
        this.inputField = document.getElementById("input-area");
        this.history = [];
        this.historyCursor = 0;
        this.init();
    }

    setEcho(value) {
        this.echoInput = value;
    }

    init() {
        this.inputField.addEventListener("keydown", (e) => {
            if (e.key === "ArrowUp") {
                if (this.historyCursor > 0) {
                    this.historyCursor--;
                    this.inputField.value = this.history[this.historyCursor];
                }
            } else if (e.key === "ArrowDown") {
                if (this.historyCursor < this.history.length) {
                    this.historyCursor++;
                    this.inputField.value = this.history[this.historyCursor] ?? "";
                }
            } else if (e.key === "Enter") {
                this.addToInputHistory(this.inputField.value);
                const val = this.inputField.value;
                this.inputField.value = "";
                if (this.echoInput) this.output.say(`> ${val}`);
                this.handler.doCommand(val);
            }
        })
    }

    addToInputHistory(str) {
        this.history.push(str);
        this.historyCursor = this.history.length;
    }
}