<template>
        <div v-if="loading" class="flex justify-center">
            <ProgressSpinner style="width: 50px; height: 50px; margin-top: 50px" strokeWidth="3" fill="transparent"/>
        </div>
        <div v-else>
            <div class="flex items-center justify-between p-2">
                <h1>
                    {{ scenario.name }}
                </h1>
                <Button
                    @click="back()" 
                    label="Load" 
                    class="flex items-center text-sm">
                        <ChevronLeftIcon name="chevron-left" class="w-4 h-5 text-white"/>        
                        <span>Back to Scenarios</span>
                    </Button> 
            </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>
                            <Button label="Send" @click="execScenario" class="mt-9 ml-4"/>
                        </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"
                                    />
                                </div>
                            </div>
                        </div>
                        <div class="flex justify-end">
                            <Button label="Submit" @click="execScenario" class=""/>
                        </div>
                    </template>
                </div>
            </div>
        </div>

        <div v-if="loading_data" class="flex justify-center">
            <ProgressSpinner style="width: 30px; height: 30px; margin: 30px" strokeWidth="6" fill="transparent"/>
        </div>
        <div v-if="data_loaded">
            <Panel class="mt-6">
                <template #header>
                <div class="flex items-center gap-2">
                    <span class="font-bold">Hermione 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_output != null">
                        <ChangeImpactOutputViewer :scenario_output="scenario_output" />
                    </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 { ChevronLeftIcon } from '@heroicons/vue/24/solid';
import axios from 'axios';
import JsonEditorVue from 'json-editor-vue';
import 'md-editor-v3/lib/style.css';
import InputText from 'primevue/inputtext';
import ProgressSpinner from 'primevue/progressspinner';
import Select from 'primevue/select';
import Textarea from 'primevue/textarea';
import { onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';


const router = useRouter();
const route = useRoute();
const value = ref('');
const scenario = ref({});
const scenario_output = 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)
// Variable to hold the interval ID
let pollingInterval = null;

onMounted(() => {
    loading.value = true
    const id = '66f4ff309766132cadc97ebf' //TODO: Remove fixed scenario id route.params.id;  

    axios.get('/scenarios/' + id )
        .then(response => {
            loading.value = false
            scenario.value  = response.data
        });
});

    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;

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

        axios.post('/scenarios/execute-async', data)
            .then(response => {
                scenario_output.value = response.data.stringOutput;
                exec_id.value = response.data.scenarioExecution_id
                // Start polling
                startPolling();
            })
            .catch(error => {
                console.error('Error executing scenario:', error);
            });
    };

    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();

                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 to start polling
function startPolling() {
    // Set polling interval (every 5 seconds in this case)
    pollingInterval = setInterval(pollBackendAPI, 2500);
    console.log("Polling started.");
}

// Function to stop polling
function stopPolling() {
    clearInterval(pollingInterval);
    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>