<script setup lang="ts">
import CodeEditorComponent from '@/components/common/CodeEditorComponent.vue'
import EncoderButton from '@/components/encoder/EncoderButtonComponent.vue'
import { ref } from 'vue'


const data : any = ref("")
const imageData = ref("")
const doShowImage = ref(false)
const inputImage = ref()

function setTextFieldValue(newData: string) {
    data.value = newData.toString()
    doShowImage.value = false
}

function showImage(newImage : string){
    imageData.value = "data:image/jpeg;base64,"+newImage
    doShowImage.value = true
}

function convertImageToBase64(file : any){
    const reader = new FileReader()
    reader.onloadend = () => {
        data.value = reader.result?.toString().split(',')[1]
        showImage(data.value)
    }
    reader.readAsDataURL(file.target.files[0])
    
}

function clear(){
    data.value = ""
    imageData.value = ""
    doShowImage.value = false
    inputImage.value.value = null
}

</script>

<template>
<div id="layoutFull" class="w-full h-full flex flex-col xl:flex-row gap-4">
    <div id="layoutLeft" class="flex flex-col w-full xl:w-1/2 h-1/3 xl:h-full gap-4">
        <div class="w-full flex flex-row place-content-between items-center">
            <label class="dark:text-white text-center">Base64 Encoder</label>
            <div class="flex flex-row items-center gap-2 overflow-x-auto">
                <button class="tool-button" @click="clear()">Clear</button>
                <EncoderButton @image:show="showImage" :code="data" operation-type="Show Image"></EncoderButton>
                <div class="w-2"></div>
                <EncoderButton @update:result="setTextFieldValue" :code="data" operation-type="Encode"></EncoderButton>
                <EncoderButton @update:result="setTextFieldValue" :code="data" operation-type="Decode"></EncoderButton>
            </div>
            
        </div>
        <div id="codeEditor" class="w-full h-full xl:h-1/3 flex flex-col">
            <CodeEditorComponent @update:updated-code="setTextFieldValue" :config="{language:'base64'}" :code="data"></CodeEditorComponent>
        </div>
        <div class="flex flex-row justify-center w-full">
            <div class="flex flex-col items-center w-fit" id="imageImporter">
                <label class="block mb-2 text-sm font-medium text-gray-900 dark:text-white" for="file_input">Upload image</label>
                <input id="imageLoader" ref="inputImage" class="file-selector" accept=".gif, .jpg, .jpeg, .png, .webm, image/gif, image/jpeg, image/png, image/webm"  type="file" @change="convertImageToBase64" />
            </div>    
        </div>
        
    </div>
    
    <div id="layoutRight" class="w-full xl:w-1/2 min-h-[66%] xl:h-full">
        <div class="border-2 rounded-lg border-gray-300 dark:border-gray-600 min-h-[50%]" v-on="doShowImage">
            <img :src="imageData"/>
        </div>
        
    </div>
</div>
    
</template>