<template>
        
            <div class="flex items-center justify-between p-2">
                <h1>
                    {{ scenario.name }}
                </h1>
                
            </div>
            <div class="flex mt-6">
                <div class="card flex flex-col gap-4 w-full">
                    <template v-if="scenario.inputs && scenario.inputs.length === 1">
                        <div class="input-container flex items-center">
                            <div class="flex-grow">
                                <label :for="scenario.inputs[0].name"><h2>{{ scenario.inputs[0].label }}</h2></label>
                                <div class="input-wrapper">
                                    <component
                                        :is="getInputComponent(scenario.inputs[0].type)"
                                        :id="scenario.inputs[0].name"
                                        v-model="formData[scenario.inputs[0].name]"
                                        :options="scenario.inputs[0].options"
                                        class="full-width-input"
                                    />
                                </div>
                            </div> 
                        </div> 
                        <div class="flex justify-center">
                            <Button :disabled="loadingStore.exectuion_loading || !isInputFilled" label="Execute" @click="execScenario" size="large" iconPos="right" icon="pi pi-cog"></Button>
                        </div>
                    </template>
                    <template v-else>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div v-for="input in scenario.inputs" :key="input.name" class="input-container">
                                <label :for="input.name"><b>{{ input.label }}</b></label>
                                <div class="input-wrapper">
                                    <component
                                        :is="getInputComponent(input.type)"
                                        :id="input.name"
                                        v-model="formData[input.name]"
                                        :options="input.options"
                                        class="full-width-input"
                                        :disabled="loadingStore.exectuion_loading"
                                    />
                                </div>
                            </div>
                        </div>
                        <div class="flex justify-center">
                            <Button :disabled="loadingStore.exectuion_loading || !isInputFilled " label="Execute" @click="execScenario" size="large" iconPos="right" icon="pi pi-cog"></Button>
                        </div>
                    </template>
                </div>
            </div>

        <div v-if="loading_data" class="flex flex-col items-center">
            <div class="flex justify-center mt-4">
                <jellyfish-loader :loading="loadingStore.exectuion_loading" scale="1" color="#A100FF" />
            </div> 
            <div v-if="scenario_response_message && scenario_response_message.includes('/')">
                <span>{{ scenario_response_message }}</span>
            </div>
            <div v-else>
                Starting execution...
            </div>
            <div class="flex justify-center" style="margin-bottom: 30px;">
                <p>Time elapsed:&nbsp;</p>
                <div id="timer" class="timer">00:00</div>
            </div>
        </div>
        <div v-if="data_loaded">
            <Panel class="mt-6">
                <template #header>
                <div class="flex items-center gap-2">
                    <span class="font-bold">Workflow Response</span>
                </div>
                </template>
                <template #icons>
                    <div class="flex justify-end">
                    <Button severity="secondary" rounded @click="openDebug" v-tooltip.left="'View code'">
                        <i class="pi pi-code"></i>
                    </Button>
                    </div>
                </template>
                
                <div class="card flex flex-col gap-4 w-full">
                    <div v-if="scenario.outputType == 'ciaOutput'">
                        <ChangeImpactOutputViewer :scenario_output="scenario_output" />    
                    </div>
                    <div v-else>
                        <MdPreview class="editor" v-model="scenario_output" language="en-US"  />
                    </div>
                </div>
             </Panel>
            <Dialog v-model:visible="debug_modal" maximizable modal :header="scenario.name" :style="{ width: '75%' }" :breakpoints="{ '1199px': '75vw', '575px': '90vw' }">
                
                <div class="flex">
                <div class="card flex flex-col gap-4 w-full">
                <JsonEditorVue
                    v-model="exec_scenario"
                />
            </div>
        </div>
    
            </Dialog>
        </div>
</template>

<script setup>

import ChangeImpactOutputViewer from '@/components/ChangeImpactOutputViewer.vue';
import { LoadingStore } from '@/stores/LoadingStore';
import axios from 'axios';
import JsonEditorVue from 'json-editor-vue';
import { MdPreview } from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';
import InputText from 'primevue/inputtext';
import Select from 'primevue/select';
import Textarea from 'primevue/textarea';
import { computed, onMounted, ref, watch } from 'vue';
import moment from 'moment';
import { useRoute, useRouter } from 'vue-router';
import { JellyfishLoader } from "vue3-spinner";

const loadingStore = LoadingStore();


const router = useRouter();
const route = useRoute();
const value = ref('');
const scenario = ref({});
const scenario_response = ref(null);
const scenario_output = ref(null);
const scenario_response_message = ref(null);
const loading = ref(false);
const data_loaded = ref(false);
const loading_data = ref(false);
const formData = ref({});
const exec_id = ref(null);
const exec_scenario = ref({});
const debug_modal = ref(false);
let pollingInterval = null;

let startTime = ref(null);
let timerInterval = ref(null);

function startTimer() {
  startTime = Date.now();
  timerInterval = setInterval(() => {
    const elapsedTime = moment.duration(Date.now() - startTime);
    document.getElementById("timer").textContent = moment.utc(elapsedTime.asMilliseconds()).format("mm:ss");
  }, 1000);
}

function stopTimer() {
    clearInterval(timerInterval);
}


const isInputFilled = computed(() => {
    var isFilled = true;
    if(scenario.value.inputs === undefined) {
        return false;
    }
    scenario.value.inputs.forEach(input => {
         if(formData.value[input.name]  === undefined || formData.value[input.name] === '') {
             isFilled= false;
        }
    });
    return isFilled;
});


onMounted(() => {
    fetchScenario(route.params.id);
});

// Ricarica i dati quando cambia il parametro `id`
watch(() => route.params.id, fetchScenario);


    //Function to fetch scenarios
    function fetchScenario(id) {
        data_loaded.value = false; 
        formData.value = {}; 
        loading.value = true;
        axios.get(`/scenarios/${id}`)
            .then(response => {
                scenario.value = response.data;
            })
            .catch(error => {
                console.error("Error fetching scenario:", error);
            })
            .finally(() => {
                loading.value = false;
            });
    }

    const getInputComponent = (type) => {
        switch (type) {
            case 'text':
                return InputText;
            case 'textarea':
                return Textarea;
            case 'select':
                return Select;
            default:
                return InputText;
        }
    };

   
    const execScenario = () => {
        loading_data.value = true;
        data_loaded.value = false;
        startTimer();

        loadingStore.exectuion_loading = true;

        const data = {
            scenario_id: scenario.value.id,
            inputs: { ...formData.value }
        };

        axios.post('/scenarios/execute-async', data)
            .then(response => {
                scenario_response.value = response.data;
                scenario_response_message.value = response.data.message;
                scenario_output.value = response.data.stringOutput;
                exec_id.value = response.data.scenarioExecution_id

                // Start polling
                startPolling();
            })
            .catch(error => {
                console.error('Error executing scenario:', error);
                loadingStore.exectuion_loading = false;
            });
    };

    const back = () => {
        router.push({ name: 'scenario-list'});
    }

    const openDebug = () => {

        axios.get('/scenarios/execute/'+ exec_id.value).then(resp =>{
            exec_scenario.value = resp.data
            debug_modal.value = true
        })
    }


    const pollBackendAPI = () => {

        axios.get('/scenarios/getExecutionProgress/'+exec_id.value).then(response => {
            if (response.data.status == 'OK' || response.data.status == 'ERROR') {
                console.log("Condition met, stopping polling.");
                stopPolling();

                stopTimer();
                loading_data.value = false;
                data_loaded.value = true;
                scenario_output.value = response.data.stringOutput;
                exec_id.value = response.data.scenarioExecution_id
                scenario_response_message.value = null //if != null, next scenario starts with old message

            } else {
                console.log("Condition not met, polling continues.");
                scenario_response.value = response.data;
                scenario_response_message.value = response.data.message;
            }
        });
    }

    // Function to start polling
    function startPolling() {
    // Set polling interval (every 2.5 seconds in this case)
        pollingInterval = setInterval(pollBackendAPI, 2500);
        console.log("Polling started.");
    }

    // Function to stop polling
    function stopPolling() {
        clearInterval(pollingInterval);
        loadingStore.exectuion_loading = false;


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

</script>

<style scoped>
    .input-container {
        margin-bottom: 1em;
    }

    .input-wrapper {
        display: flex;
        align-items: center; 
        gap: 0.5em; 
        margin-top: 10px;
    }

    .full-width-input {
        width: 100%;
    }


.editor ol {
    list-style-type: decimal !important;
}

.editor ul {
    list-style-type: disc !important;
}
 
</style>