<template>
<div class="root">
    <textarea class="text-input input-area" @input="onTextInput"
        v-model="input" :placeholder="translations.get('DirectInput_InputPlaceholder')" />
    <div class="text-container">
        {{ output }}
    </div>

    <button class="btn-primary right-column" :disabled="!canDownload" @click="downloadAsText">Download</button>
</div>
</template>

<style scoped lang="scss">
.root {
    display: grid;
    grid-template-columns: 1fr 1fr;
    grid-template-rows: auto auto;
    gap: 1em;
}

.input-area {
    resize: none;
    min-height: 4em;
    overflow: hidden;
}

.right-column {
    grid-column: 2;
}
</style>

<script>
import { mapState } from "vuex";
import { saveAs } from "file-saver"
import MacronRestorationModule from "../js/MacronRestorationModule"

const macroniser = new MacronRestorationModule();

export default {
    name: "DirectInput",
    data() {
        return {
            input: "",
            output: "",
            transcribeTimeout: null,
            waitingOnTranscribe: false
        }
    },
    computed: {
        canDownload() {
            return this.output.length > 0 && !this.waitingOnTranscribe;
        },
        ...mapState({
            translations: state => state.translations
        })
    },
    watch: {
        input() {
            this.waitingOnTranscribe = true;

            if (this.transcribeTimeout !== null) {
                clearTimeout(this.transcribeTimeout);
            }

            this.transcribeTimeout = setTimeout(this.updateMacronisedText, 1000);
        }
    },
    methods: {
        /**
         * Handles input on an element, and grows its height so that the text is always visible.
         * @param {InputEvent} event The input event.
         */
        onTextInput(event) {
            event.target.height = event.target.scrollHeight;
        },
        async updateMacronisedText() {
            // TODO: Handle error
            const response = await macroniser.directMacronisation(this.input);
            this.output = response.fragment2;
            this.waitingOnTranscribe = false;
        },
        downloadAsText() {
            const blob = new Blob([ this.output ], { type: "text/plain;charset=utf-8" });
            saveAs(blob, "output.txt");
        }
    }
}
</script>
