<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" 
                    @click="openToastRE" 
                    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"  color="#a100ff" 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>

      <!-- Dialog per selezionare lo scenario -->
      <Dialog v-model:visible="showScenarioDialog" header="Select a Scenario" :closable="false" :modal="true" style="width: 400px;">
        <div>
            <Dropdown 
    v-model="selectedScenario" 
    :options="scenario_store.scenariosForRE" 
    optionLabel="name" 
    placeholder="Select a Scenario" 
    class="w-full" 
  />        </div>
        <div class="flex justify-end mt-3">
            <Button label="Cancel" severity="secondary" @click="showScenarioDialog = false" class="mr-2" />
            <Button label="Execute" severity="primary" :disabled="!selectedScenario" @click="executeScenario" />
        </div>
    </Dialog>
   
</template>

<script setup>

import { ApplicationCodeService } from '@/service/ApplicationCodeService';
import { LoadingStore } from '@/stores/LoadingStore';
import { ScenarioStore } from '@/stores/ScenarioStore';
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 { useConfirm } from 'primevue/useconfirm';
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 confirm = useConfirm();
const { className } = toRefs(props);
const  classDetails  = ref(null);
const  classLoaded  = ref(false);
const loadingStore = LoadingStore();
const scenario_store = ScenarioStore();
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 showScenarioDialog = ref(false); // Controlla la visibilità del dialog
const selectedScenario = ref(null); // Lo scenario selezionato
const scenarios = ref([]); // Lista degli scenari disponibili
const commonRevRequest = reactive({
  repositoryEntityId: '',
  applicationName: '',
  applicationProjectName: '',
  fullClassQualifiedName: '',
  applicationVersion: '',
  deleteExistingData: true, // Valore booleano
  applicationType: '',
  commitSha: '',
  scenarioId: ''
});

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

});



// Mostra il dialog quando si clicca il pulsante
const openToastRE = () => {
    showScenarioDialog.value = true;
};

// Esegue l'azione con lo scenario selezionato
const executeScenario = () => {
    if (!selectedScenario.value) {
        toast.add({
            severity: 'warn',
            summary: 'Attenzione',
            detail: 'Seleziona uno scenario prima di continuare',
            life: 3000
        });
        return;
    }

    // Imposta l'ID dello scenario
    commonRevRequest.scenarioId = selectedScenario.value.id;

    // Nasconde il dialog e chiama la funzione per l'RE
    showScenarioDialog.value = false;
    doREClass();
};

function checkExtension() {
      // Ottieni la parte dopo il punto
      const extension = userPrefStore.getSelFile.split('.').pop();
      
      // Controlla se è "java"
      if (extension === 'java' || extension === 'jsp') {
        commonRevRequest.applicationType = extension;
      } else {
        commonRevRequest.applicationType = 'GENERIC';
      }
    
    };

// Logica per eseguire l'RE
const doREClass = () => {
    commonRevRequest.fullClassQualifiedName = props.className;
    checkExtension();
    console.log("commonRevRequest.fullClassQualifiedName", commonRevRequest.fullClassQualifiedName);
    commonRevRequest.applicationName = userPrefStore.getSelApp.internal_name;
    commonRevRequest.applicationProjectName = userPrefStore.selectedProject.internal_name;

    ApplicationCodeService.doRevEngForSingleClass(commonRevRequest)
        .then(response => {
            if (response.data !== "KO") {
                startPolling(response.data);
            } else {
                toast.add({
                    severity: 'error',
                    summary: 'Errore',
                    detail: 'Si è verificato un errore. Riprova più tardi.',
                    life: 3000
                });
            }
        });
};

/*const openToastRE = () => {
    confirm.require({
        message: 'Do you want to proceed for the Reverse Engeeniring for this class?',
        header: 'RE Confirmation',
        icon: 'pi pi-exclamation-triangle',
        accept: () => {
            doREClass();
        }
});
}

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("tab update: ",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("updateSelectedMethod",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 = [];
    console.log("classDetails.value.methods", classDetails.value.methods);
    classDetails.value.methods.forEach(method => {
        methods.push({name: method.split(".").slice(-1)[0], value: method});
    });
    console.log("methods", methods);
    methods.sort((a, b) => a.name.localeCompare(b.name));
    console.log("methods ordered", methods);
    return methods;
}

</script>

<style>




</style>
