<script setup lang="ts">
import TabComponent from './TabComponent.vue'
import InsertTemplateComponent from '@components/common/InsertTemplateComponent.vue'
import XMLButtonFormatterComponent from '@components/formatter/XMLButtonFormatterComponent.vue'
import { type TabData } from '../common/TabData'
import { ref } from 'vue'
import CodeEditor from '@/components/common/CodeEditorComponent.vue';

const props = defineProps(
    {
        stylizedName: {type: String, required: true},
        data: {type: Array<TabData>},
        tabCountLimit: {type: Number, required: false, validator: (value) => typeof value == "number" && value > 0}
    }
)
const emit = defineEmits(['update:modelValue'])

const newTabId = ref(0);
const activeTabId = ref(0);
const data = ref('')
const inputFile = ref()

const tabs = ref(new Array<TabData>);
tabs.value.push({
    id: newTabId.value++,
    name: "xml1.xml",
    data: "",
})

function sendValue() {
    emit('update:modelValue', tabs.value);
}

function updateData(newData: string) {
    data.value = newData;
    tabs.value.at(findIndexWithID(activeTabId.value))!.data = newData;
    inputFile.value.value = '';
    sendValue();
}

function clear() {
    updateData('');
}

function canBeFormatted() {
    return props.stylizedName.toLowerCase() == 'xml' || 
           props.stylizedName.toLowerCase() == 'xsd' || 
           props.stylizedName.toLowerCase() == 'xslt'
}

function readFile(file : any) {
    
    const reader = new FileReader()
    reader.onloadend = () => {
        let result = reader.result!.toString();
        
        let activeIndex = findIndexWithID(activeTabId.value);
        
        let filePath = inputFile.value.value.split("\\");
        let fileName = filePath.at(filePath.length - 1);
        
        tabs.value.at(activeIndex)!.name = fileName;
        updateData(result);
        
    }
    reader.readAsText(file.target.files[0]);
    
}

function changeActiveTab(id : number) {
    let index = findIndexWithID(activeTabId.value);
    let newIndex = findIndexWithID(id);
    
    tabs.value.at(index)!.data = data.value;
    activeTabId.value = id;
    data.value = tabs.value.at(newIndex)!.data;

    sendValue();
}

function addTab() {
    if (isTabCountLimitAchieved())
        return

    tabs.value.push({
        id: newTabId.value++,
        name: "xml" + newTabId.value + ".xml",
        data: ""
    });
}

function isTabCountLimitAchieved() {
    return props.tabCountLimit && tabs.value.length == props.tabCountLimit
}

function removeTab(id : number) {
    if (tabs.value.length == 1)
        return

    let indexToRemove = findIndexWithID(id);

    switchToExistingTab(indexToRemove);
    
    tabs.value.splice(indexToRemove, 1);
    
}

function switchToExistingTab(indexToRemove: number) {
    let activeIndex = findIndexWithID(activeTabId.value);

    if (indexToRemove == activeIndex && activeIndex == 0)
        changeActiveTab(tabs.value.at(1)!.id)
    else if (indexToRemove == activeIndex)
        changeActiveTab(tabs.value.at(0)!.id)
}

function findIndexWithID(id : number) : number {
    for (let i = 0; tabs.value.length; i++) 
        if (tabs.value.at(i)!.id == id)
            return i;
    
    return -1;
}

</script>

<template>
    <div class="flex flex-col w-full h-1/2 lg:h-1/2 flex-none xl:pr-2 2xl:pr-4 pb-2">
        <div class="flex justify-between mb-2">
            <div class="flex gap-2 overflow-x-auto">
                <TabComponent @click:activate="changeActiveTab" @click:remove="removeTab" v-for="tab in tabs" :id="tab.id" :isActive="tab.id == activeTabId">{{ tab.name }}</TabComponent>
            </div>
            <div class="flex gap-2">
                <div class="flex items-stretch w-64">
                    <input id="fileLoader" ref="inputFile" class="file-selector" type="file" accept=".xml,.xql,.xquery,.xslt,text/xml,text/plain" @change="readFile" />
                </div>
                <button :class="isTabCountLimitAchieved() ? 'inactive-button' : 'tool-button'" @click="addTab">New</button>
            </div>
        </div>
        
        <div class="flex place-content-between w-full items-center">
            <span class="dark:text-white mr-2">{{ stylizedName }}</span>
            <div class="flex space-x-2 pb-2 overflow-x-auto">
                <InsertTemplateComponent :stylized-name="props.stylizedName" @update:default-data="updateData"></InsertTemplateComponent>
                <XMLButtonFormatterComponent v-if="canBeFormatted()" :xml="data" @update:result="(data:any) => updateData(data.result)"></XMLButtonFormatterComponent>
                <button class="tool-button" @click="clear">Clear</button>
            </div>
        </div>
        <CodeEditor @update:updated-code="updateData" v-model="data" :code="data" :config="{disabled:false, language:stylizedName}"></CodeEditor>
    </div>
</template>