<template>
    <div class="card mt-1">
        <div class="card-header">Console</div>
        <div class="card-body">
            <div class="row">
                <div class="col">
                    <textarea readonly rows="10" ref="console" class="form-control form-control-sm">{{ consoleLog }}</textarea>
                </div>
            </div>
            <div class="row">
                <div class="col mt-1">
                    <input v-model="command" :disabled="disabled" v-on:keyup.enter="sendCommand(this.command)" v-on:keyup="keyUp" type="text" class="form-control form-control-sm">
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        props: {
            consoleLog: '',
            disabled: Boolean
        },
        data: function () {
            return {
                command: this.command,
                history: [],
                historyIndex: 0
            }
        },
        methods: {
            sendCommand () {
                this.$emit('sendCommand', this.command)
                this.history.push(this.command)
                this.historyIndex = this.history.length
                this.command = ''
            },

            keyUp(event) {
                if (event.key == 'ArrowUp') {
                    if (this.historyIndex > 0) { 
                        this.historyIndex--
                        this.command = this.history[this.historyIndex]
                    }
                }
                if (event.key == 'ArrowDown') {
                    if (this.historyIndex < this.history.length) { 
                        this.historyIndex++
                        this.command = this.history[this.historyIndex]
                    }
                }
            }
        },
        watch: {
            async consoleLog() {
                setTimeout(()=>{
                    let textArea = this.$refs['console']
                    textArea.scrollTop = textArea.scrollHeight
                }, 100);
            },
        }
    }
</script>

<style>

</style>