// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// % CONSOLE

var commandHistory = []; // Stores commands executed by console.

var histIndex = -1; // Selected element of 'commandHistory'. (-1 = "")

function createContentConsole(s) {
    // Creates input-textfield and texarea showing console-history.

    var commandline = document.createElement('input');
    commandline.type = "text";
    commandline.classList.add("row", "commandline");

    commandline.onkeydown = function (e) {
        //console.log(histIndex);
        if (e.which === 38 || e.key == "ArrowUp") {
            if (histIndex + 1 < commandHistory.length) {
                histIndex++;
                this.value = commandHistory[histIndex];
            }
            var input = this;
            window.setTimeout(
                    function () {
                        input.setSelectionRange(input.value.length,
                                input.value.length);
                    }, 0, input);
        }
        if (e.which === 40 || e.key == "ArrowDown") {
            if (histIndex >= 0) {
                histIndex--;
                if (histIndex > -1) {
                    this.value = commandHistory[histIndex];
                } else {
                    this.value = "";
                }
            }
        }
    };

    commandline.autocomplete = "on";

    var wrapper = document.createElement('form');
    wrapper.classList.add("commandline-wrapper");

    wrapper.onsubmit = function (e) {
        e.preventDefault();
        histIndex = -1;
        // Request for command.
        reqJSON(s, "http://" + hostPort + "/sendcommand?command="
                + commandline.value + "&id=" + clientID, successHandler,
                errorHandler);
        commandline.value = "";
    };

    wrapper.method = "GET";
    wrapper.appendChild(commandline);

    var history = document.createElement('div');
    history.classList.add("history");

    var content = document.createElement('div');
    content.classList.add("content-console");
    content.appendChild(wrapper);
    content.appendChild(history);
    return content;
}
