<template> 
    <div class="flex items-center justify-between p-2">
            <h1>
                Source Code Explorer  : {{userPrefStore.getSelApp.fe_name}}
            </h1>
    </div>

    <div class="flex gap-2">
        <div class="card folder-tree">
            <h5>File Browser</h5>
            <div v-if="nodes && nodes.length" class="flex-1">
                <div class="flex flex-wrap gap-2">
                    <Button type="button" icon="pi pi-plus" label="Expand All" @click="expandAll"></Button>
                    <Button type="button" icon="pi pi-minus" label="Collapse All" @click="collapseAll"></Button>
                </div>
                <Tree :value="nodes" @nodeSelect="onNodeSelect" selectionMode="single" :expandedKeys="expandedKeys" @nodeExpand="expandNode" @nodeCollapse="collapseNode" :filter="true" filterMode="lenient" class="w-full"></Tree>
            </div>
            <div v-else class="flex-skeleton">
                <Skeleton v-for="(config, index) in skeletonConfigs"
                    :key="index"
                    :width="config.width"
                    :height="config.height"
                    class="mb-2 w-full"
                    style="background-color: #e7e7e8" />
            </div>
        </div>    
        <div id ="card-flow-codeviewer" class="flex-1">
            <div class="card flow-codeviewer">  
                <h5>File Explorer</h5>
                <p v-if="nodes && nodes.length"> 
                    <FileFlowViewer :file="selectedFile" :application="userPrefStore.getSelApp.fe_name"/>
                </p>
            </div>
        </div>
    </div>
</template>

<script setup>  

import FileFlowViewer from '@/components/FileFlowViewer.vue';
import { ApplicationCodeService } from '@/service/ApplicationCodeService';
import { LoadingStore } from '@/stores/LoadingStore.js';
import { ScenarioStore } from '@/stores/ScenarioStore.js';
import { UserPrefStore } from '@/stores/UserPrefStore.js';
import Tree from 'primevue/tree';
import { onMounted, ref, watch } from 'vue';
import { useRouter } from 'vue-router';

const nodes = ref(null)
const expandedKeys = ref({});
const selectedFile = ref({})
const router = useRouter();
const userPrefStore = UserPrefStore();
const loadingStore = LoadingStore()
const scenario_store = ScenarioStore();

onMounted(() => {
    console.log("Mounted")
    fetchApplicationData();
    scenario_store.fetchScenariosForRE();

})

function fetchApplicationData() {
    nodes.value = null;
    LoadingStore.another_loading = true;
    ApplicationCodeService.getApplication(userPrefStore.getSelApp.internal_name)
        .then(response => {
            const tmp = []
            tmp.push(response.data)
            nodes.value = tmp
            expandAll()   
            LoadingStore.another_loading = false;
        })
        .catch(error => {
            console.error("Error fetching application data:", error)
            LoadingStore.another_loading = false;
            collapseAll();
        })
}

function reloadPage() {
        console.log("collapse all");
        collapseAll();
        console.log("reloadPage");
        fetchApplicationData();
}

watch(() => userPrefStore.getSelApp, reloadPage, { immediate: true });

function onNodeSelect(e){
    if(e.icon == "pi pi-fw pi-file"){
        selectedFile.value = e.key
    }
    userPrefStore.setSelectedFile(e.label)
    console.log("user pref store file", userPrefStore.getSelFile)
    console.log(e)
};


const expandAll = () => {
    for (let node of nodes.value) {
        expandNode(node, true);
    }
    expandedKeys.value = { ...expandedKeys.value };
};

const collapseAll = () => {
    expandedKeys.value = {};
};

const expandNode = (node, expandAllChildren = false) => {
    if (node.children && node.children.length) {
        expandedKeys.value[node.key] = true;
        if (expandAllChildren) {
            node.children.forEach(child => {
                expandNode(child, expandAllChildren);
            });
        } else {
            expandedKeys.value[node.children.key] = true;
        }
    }
    expandedKeys.value = { ...expandedKeys.value };
};

const collapseNode = (node) => {
    if (node.children && node.children.length) {
       node.children.forEach(child => {
            delete expandedKeys.value[child.key];
        });
    }
    expandedKeys.value = { ...expandedKeys.value };
};

const skeletonConfigs = [
    { width: "30%", height: "3rem", inline: true },
    { width: "95%", height: "3rem" },
    { width: "50%", height: "1.5rem" },
    { width: "60%", height: "1.5rem" },
    { width: "70%", height: "1.5rem" },
    { width: "80%", height: "1.5rem" },
    { width: "80%", height: "1.5rem" },
    { width: "70%", height: "1.5rem" },
    { width: "80%", height: "1.5rem" },
    { width: "70%", height: "1.5rem" },
    { width: "80%", height: "1.5rem" },
    { width: "80%", height: "1.5rem" },
    { width: "80%", height: "1.5rem" },
    { width: "70%", height: "1.5rem" },
    { width: "80%", height: "1.5rem" }
];

watch(selectedFile, () => {
    if (selectedFile.value) {
        const cardFlowCodeViewer = document.getElementById('card-flow-codeviewer');
        if (cardFlowCodeViewer) {
            window.scrollTo({ top: 0, behavior: 'smooth' });
        }
    }
});

</script>


<style>
.folder-tree {
    min-height: 75vh;
    overflow: auto;
}

.p-inputtext {
    width: 100%;
}

.flow-codeviewer {
    height: 75vh;
}

.flex-skeleton {
  flex: 1;
  min-width: 350px;
  text-align: center;
}
</style>