<template>
<div class="main-page-root">
    <modal-dialog v-if="modal.show" :title="modal.title" :description="modal.description" :buttons="modal.buttons" @close="onModalClose" />
    <edit-page v-if="showEditor" class="image-editor" :src="imageUrl" :imageBuffer="imageBuffer"
        @closeAndDiscard="onEditorCloseRequested" @closeAndSave="onEditorSave" />

    <div class="paper root-container" :class="{ 'root-container-image-state': imageUrl !== null }">
        <div v-if="imageUrl === null" class="upload-area" @click="uploadFile">
            <span class="heading1">{{ translations.get("Title") }}</span>
            <span class="material-icons mdi-xl">upload_file</span>
            <span>{{ translations.get("MainPage_Upload") }}</span>
        </div>

        <div v-if="imageUrl !== null" class="image-area">
            <div class="controls">
                <button class="btn-primary" @click="doOcr" :disabled="ocrInProgress">
                    <span class="material-icons">play_arrow</span>
                    <span>{{ translations.get("MainPage_PerformOCR") }}</span>
                </button>

                <button class="btn-primary" @click="showEditor = true" :disabled="ocrInProgress">
                    <span class="material-icons">edit</span>
                    <span>{{ translations.get("MainPage_EditImage") }}</span>
                </button>

                <button class="btn-primary" @click="reset(false)" :disabled="ocrInProgress">
                    <span class="material-icons">restart_alt</span>
                    <span>{{ translations.get("MainPage_NewImage") }}</span>
                </button>
            </div>

            <div class="progress-bar-container ocr-progress">
                <div v-if="ocrInProgress" class="progress-bar-value progress-bar-indeterminate" />
            </div>

            <img class="image-display" :src="imageUrl" />

            <div class="text-container">
                <span v-if="ocrResult === null && !ocrInProgress" class="text-placeholder">{{ translations.get("MainPage_OCRHint") }}</span>
                <pre>{{ ocrResult }}</pre>
            </div>
        </div>
    </div>

    <input ref="fileInput" type="file" @input="onFilesChanged" class="hidden"
        accept="image/png,image/jpeg,image/gif,image/bmp,image/tiff,image/webp,application/pdf" />
</div>

</template>

<style lang="scss" scoped>
.main-page-root {
    display: flex;
    align-items: center;
    justify-content: center;
}

.root-container {
    padding: 1em;
    transition-duration: var(--transition-duration);
}

.root-container-image-state {
    width: calc(100% - 3em);
    height: calc(100vh - 3em);
    max-height: calc(100vh - 3em);
}

.upload-area {
    display: grid;
    grid-template-columns: auto auto;
    grid-template-rows: auto 1fr;
    align-items: center;
    justify-items: center;

    padding: 2em;
    gap: 1em;

    font-size: 2rem;
    cursor: pointer;
    border: 3px dashed var(--bg-color);
    border-radius: var(--border-radius);

    .heading1 {
        grid-column-start: span 2;
        color: #666;
    }
}

.hidden {
    display: none;
}

.image-editor {
    position: absolute;
    height: 100%;
    width: 100%;
    top: 0;
    left: 0;
    z-index: 9;
}

.image-area {
    display: grid;
    grid-template-columns: 1fr 1fr;
    grid-template-rows: auto auto 1fr;
    height: 100%;

    gap: 1rem;
    align-items: center;
    justify-items: center;

    position: relative;
    overflow: hidden;

    .text-container {
        height: 100%;
        width: 100%;
    }
}

.image-display {
    border: 1px solid #444;
    max-width: 100%;
    max-height: 80vh;
    object-fit: contain;
}

.controls {
    display: flex;
    gap: 1em;
    grid-column-start: span 2;
}

.ocr-progress {
    grid-column-start: span 2;
}

.text-container {
    overflow: scroll;
}
</style>

<script>
import { mapState } from "vuex";
import EditPage from "./EditPage.vue";
import ModalDialog from "./ModalDialog.vue"
import OcrService, { OcrOptions } from "../js/OcrService"
import { log } from "../js/Util";

const ocrService = new OcrService();

export default {
    name: "MainPage",
    components: {
        EditPage,
        ModalDialog
    },
    data() {
        return {
            imageType: null,
            /** @type {ArrayBuffer} */
            imageBuffer: null,
            imageUrl: null,
            ocrInProgress: false,
            ocrResult: null,
            showEditor: false,
            modal: {
                show: false,
                title: "",
                description: "",
                buttons: []
            }
        }
    },
    computed: {
        ...mapState({
            translations: state => state.translations
        })
    },
    watch: {
        imageBuffer(newValue) {
            if (this.imageUrl !== null) {
                URL.revokeObjectURL(this.imageUrl);
            }

            if (newValue === null) {
                return;
            }

            const arrayView = new Uint8Array(newValue);
            const blob = new Blob([ arrayView ]);
            this.imageUrl = URL.createObjectURL(blob);
        }
    },
    methods: {
        uploadFile() {
            this.$refs.fileInput.click();
        },
        async onFilesChanged() {
            /** @type {File[]} */
            const files = this.$refs.fileInput.files;
            if (files === null || files === undefined || files.length !== 1) {
                return;
            }

            this.imageBuffer = await files[0].arrayBuffer();
            this.imageType = files[0].type;
        },

        async doOcr() {
            try {
                this.ocrInProgress = true;

                const arrayView = new Uint8Array(this.imageBuffer);
                const imageBlob = new Blob([ arrayView ], { type: this.imageType });

                const result = await ocrService.run([
                    {
                        image: imageBlob,
                        fileName: "file.png",
                        options: new OcrOptions(false)
                    }
                ]);

                this.ocrResult = result[0].text;
            }
            catch (ex) {
                // TODO: Display error
                log("Failed to perform OCR", "error");
                log(ex, "error");
            }
            finally {
                this.ocrInProgress = false;
            }
        },

        onEditorCloseRequested() {
            this.showEditor = false;
        },
        /**
         * Called when the editor is saved in order to update the stored image buffer.
         * @param {Buffer} newBuffer The updated image buffer.
         * @param {String} newType The updated MIME type of the image buffer.
         */
        onEditorSave(newBuffer, newType) {
            this.imageBuffer = newBuffer.buffer;
            this.imageType = newType;

            this.onEditorCloseRequested();
        },

        reset(hard) {
            if (!hard) {
                // TODO: Translate
                this.modal.title = this.translations.get("NewImageModal_Title");
                this.modal.description = this.translations.get("NewImageModal_Description");
                this.modal.buttons = [
                    this.translations.get("NewImageModal_ButtonContinue"),
                    this.translations.get("NewImageModal_ButtonCancel")
                ]
                this.modal.resetConfirmation = true;
                this.modal.show = true;

                return;
            }

            URL.revokeObjectURL(this.imageUrl);
            this.imageUrl = null;
            this.ocrInProgress = false;
            this.ocrResult = null;
            this.showEditor = false;
            this.$refs.fileInput.value = "";
        },

        onModalClose(button) {
            this.modal.show = false;

            if (this.modal.resetConfirmation) {
                if (button === "Continue") {
                    this.reset(true);
                }

                this.modal.resetConfirmation = false;
            }
        }
    }
}
</script>
