<template>
    <Tabs value="class-code" @update:value="tabUpdate">
        
        <TabList>            
            <Tab value="class-code">Class Code</Tab>
            <Tab value="class-description">Class RE</Tab>
            <Tab v-if="methods != null" value="method-list">Method List</Tab>
        </TabList>
        <TabPanels>
        
           
           
            <TabPanel value="class-code">    
                    <p v-if="classLoaded" class="m-0"> 

                        <HighCode
                        class="code"
                        :codeValue="classDetails.code"
                        theme="light"
                        width="100%"
                        height="100%"
                        :codeLines="true"
                        fontSize="14px"
                        ></HighCode>
                    </p>
                    <Skeleton v-else width="100%" height="10rem"></Skeleton>

                
               
            </TabPanel> 
            <TabPanel value="class-description">
                <div class="flex justify-end">
                    <Button label="Execute RE Class" 
                    severity="secondary" 
                    rounded @click="doREClass" 
                    v-tooltip.left="'Execute reverse engeenering for the class selected'"
                    :disabled="loadingStore.re_loading">
                        
                    </Button>
                    </div>

                    <div v-if="loadingStore.re_loading" class="flex justify-center">
                         <jellyfish-loader :loading="loadingStore.re_loading"  scale="1" />
            <!--<ProgressSpinner style="width: 30px; height: 30px; margin: 30px" strokeWidth="6" fill="transparent"/>-->
                </div>
                <div v-if="!loadingStore.re_loading">

               
                <p class="m-0" v-if="classLoaded">
                    <MdPreview v-if="classDetails.reDescription != null" class="editor" v-model="classDetails.reDescription" language="en-US"  />
                    <p v-else> No Description available for this class</p>
                </p>
                <Skeleton v-else width="100%" height="10rem"></Skeleton>
                </div>
            </TabPanel>
            <TabPanel v-if="methods != null" value="method-list">

                <div  v-if="classLoaded" class="grid grid-cols-12 gap-2">
                    <div class="col-span-3">
                        <div class="card folder-tree ">
                            <h5>Method List</h5>
                                <Listbox v-model="selectedMethodName" :options="methods" @update:modelValue="updateSelectedMethod" optionLabel="name" class="w-full " />
                        </div>
                    </div>
                    <div class="col-span-9">
                        <div v-if="!loadingMethod && selectedMethodDetails != null && selectedMethodDetails.reDescription == null" class="card flow-codeviewer">  
                            <h5>Method Code ( No reverse engineering available )</h5>
                            <HighCode
                                class="code"
                                :codeValue="selectedMethodDetails.code"
                                v-model="selectedMethodDetails.code"
                                theme="light"
                                width="100%"
                                height="80%"
                                :codeLines="true"
                                fontSize="14px"
                                ></HighCode>

                        </div>
                        <div v-if="!loadingMethod && selectedMethodDetails != null && selectedMethodDetails.reDescription != null" class="card flow-codeviewer">  
                            <h5>Method Explaination</h5>
                            <MdPreview class="editor" v-model="selectedMethodDetails.reDescription" language="en-US"  />


                        </div>
                        <Skeleton v-if="loadingMethod" width="100%" height="10rem"></Skeleton>

                    </div>
                </div>
                
                <Skeleton v-else width="100%" height="10rem"></Skeleton>

            </TabPanel>
        </TabPanels>
    </Tabs>
   
</template>

<script setup>

import { ApplicationCodeService } from '@/service/ApplicationCodeService';
import { LoadingStore } from '@/stores/LoadingStore';
import { UserPrefStore } from '@/stores/UserPrefStore.js';
import axios from 'axios';
import { MdPreview } from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';
import Tab from 'primevue/tab';
import TabList from 'primevue/tablist';
import TabPanel from 'primevue/tabpanel';
import TabPanels from 'primevue/tabpanels';
import Tabs from 'primevue/tabs';
import { useToast } from 'primevue/usetoast';
import { defineProps, onMounted, reactive, ref, toRefs } from 'vue';
import { HighCode } from 'vue-highlight-code';
import 'vue-highlight-code/dist/style.css';
import { JellyfishLoader } from "vue3-spinner";
import { useLayout } from './useLayout';





//66f55e4b2894530b1c154f69
const props = defineProps({
className: {
    type: String,
    required: true
}
});

const { className } = toRefs(props);
const  classDetails  = ref(null);
const  classLoaded  = ref(false);
const loadingStore = LoadingStore();
const nodes = ref(null)
const edges = ref(null)
const dark = ref(false)
const selectedMethodName = ref(null)
const selectedMethodDetails = ref(null)
const loadingMethod = ref(false)
const methods = ref(null)
let pollingInterval = null;
const userPrefStore = UserPrefStore();
const toast = useToast();
const loading_data = ref(false);
const { graph, layout, previousDirection } = useLayout()
const commonRevRequest = reactive({
  repositoryEntityId: '',
  applicationName: '',
  applicationProjectName: '',
  fullClassQualifiedName: '',
  applicationVersion: '',
  deleteExistingData: true, // Valore booleano
  applicationType: 'JAVA',
  commitSha: ''
});

onMounted(() => {
    loadClassDetails();
    console.log("class details: ", classDetails.value);
    console.log("class name: ", className.value);

});

const doREClass = () => {

    commonRevRequest.fullClassQualifiedName = className.value;
    commonRevRequest.applicationName = userPrefStore.getSelApp.internal_name;
    commonRevRequest.applicationProjectName = userPrefStore.selectedProject.internal_name;

    ApplicationCodeService.doRevEngForSingleClass(commonRevRequest).then(response => {
        console.log("RE Class response : ", response.data);
        if(response.data != "KO"){
            startPolling(response.data);
        }else{
            toast.add({
                 severity: 'error', // Tipo di notifica (errore)
                 summary: 'Errore', // Titolo della notifica
                 detail: 'Si è verificato un errore. Riprova più tardi.', // Messaggio dettagliato
                 life: 3000 // Durata della notifica in millisecondi
             });
        }
        
       
    })
}

  // Function to start polling
  function startPolling(processId) {
    // Set polling interval (every 5 seconds in this case)
        loading_data.value = true;
        loadingStore.re_loading = true;
        pollingInterval = setInterval(() => pollREBackendAPI(processId), 5000);
        console.log("Polling started.");
        
    }

    // Function to stop polling
    function stopPolling() {
        clearInterval(pollingInterval);
        loadingStore.re_loading = false;
        loading_data.value = false;
        loadClassDetails();

        console.log("Polling stopped.");
    }

    const pollREBackendAPI = (processId) => {

axios.get('/java-re-module/getProgressRevSingleClass/'+processId).then(response => {

    //console.log("Polling response : ", response);

    if(response.data.status === "DONE"){
        console.log("status done")
        stopPolling();

    }else if(response.data.status === "ERROR" || response.status === 404 ||  response.status === 500){
        console.log("status error")
        stopPolling();
        toast.add({
                 severity: 'error', // Tipo di notifica (errore)
                 summary: 'Errore', // Titolo della notifica
                 detail: 'Si è verificato un errore. Riprova più tardi.', // Messaggio dettagliato
                 life: 3000 // Durata della notifica in millisecondi
             });
    }

    //stopPolling();
    
    /*if (response.data.status == 'OK' || response.data.status == 'ERROR') {
        console.log("Condition met, stopping polling.");
        stopPolling();

        loading_data.value = false;
        data_loaded.value = true;
        scenario_output.value = response.data.stringOutput;
        exec_id.value = response.data.scenarioExecution_id

    } else {
        console.log("Condition not met, polling continues.");
    }*/
});
}

function tabUpdate(value) {
    console.log(value);
    if ((value === 'class-description'  || value ==='class-code') && classLoaded.value === false) {
        loadClassDetails()
    }
}

function updateSelectedMethod(value) {
    console.log("Selected Method : ", value);
    if (value == null) {
        return;
    }
    if(selectedMethodDetails.value != null && value.value == selectedMethodDetails.value.fullyQualifiedName ) {
        return;
    }
    loadingMethod.value = true;
    axios.get("/source-module/getMethodDetailedInfo?methodName=" +  value.value  ).then(resp => {
        console.log(resp.data);
        selectedMethodDetails.value = resp.data;
        loadingMethod.value = false;
    })
}

function loadClassDetails() {
    console.log("Getting class details : ", className.value);
    axios.get("/source-module/getClassDetailedInfo?className=" +  className.value ).then(resp => {
        classDetails.value = resp.data;
        if (classDetails.value.methods != null) {
            methods.value = createMethodList();
        }
        
        classLoaded.value = true;
    })
    .catch(error => {
        console.error('Error during the request:', error);
    });
}

function createMethodList() {
    let methods = [];
    classDetails.value.methods.forEach(method => {
        methods.push({name: method.split(".").slice(-1)[0], value: method});
    });
    return methods;
}

</script>

<style>


</style>
