<template>
        <div className="card">
        <Dialog v-model:visible="execScenarioDialogVisible" modal :header="execScenario.name" :style="{ width: '70rem' }">
            <ScenarioExctuotionDialog :scenario="execScenario" @add="addFromDialog"/>
        </Dialog>
        <Dialog v-model:visible="execHermioneDialogVisible" modal :header="modalTitle" :style="{ width: '70rem' }">
            <div v-if="askDialog" class="card flex flex-col gap-4 p-1">
                <div class="flex flex-col gap-2">
                    <InputText id="question" type="text" placeholder="Write a Question" v-model="userQuestion" />
                </div>    
                <div class="flex justify-center">
                    <Button label="Submit" @click="askHermione()" class=""/>
                </div>
            </div>

            <div class="flex justify-center items-center">
                <ProgressSpinner v-if="loadingData" style="width: 50px; height: 50px" strokeWidth="8" fill="transparent"
                animationDuration=".5s" aria-label="Custom ProgressSpinner" />
            </div>

            <div v-if="dataLoaded" class="card flex flex-col gap-4 p-1">       
                <div class="flex items-center gap-2 p-0">
                    <button class="p-button p-button-primary" @click="addFromDialog()">Add to Canvas</button>
                </div>     
                <div class="flex mt-2">
                    <Editor v-model="response" editorStyle="height: 320px" />
                </div>
            </div> 
        </Dialog>
        <Editor  v-model="content"  editorStyle="height: 600px" @contextmenu="onRightClick" @selection-change="onSelectionChange" />
        <ContextMenu ref="menu" :model="items"  :style="{'white-space':'nowrap', 'width': 'auto'}" />
    </div>
</template>

<script setup>
    import { ScenarioService } from '@/service/ScenarioService.js';
import ScenarioExctuotionDialog from '@/views/pages/canvas/ScenarioExecutionDialog.vue';
import axios from 'axios';
import { computed, onMounted, ref } from 'vue';

    const menu = ref();
    const currentSelection = ref(null);
    const currentPosition = ref(null);
    const content = ref('Welcome to Olympus Canvas....');
    const scenarios = ref([]);
    const items = ref([]);
    const execScenarioDialogVisible = ref(false);
    const execScenario = ref({name:""});
    const userQuestion = ref(null)
    const execHermioneDialogVisible = ref(false)
    const response = ref('')
    const dataLoaded = ref(false)
    const loadingData = ref(false)
    const askDialog = ref(false)
    const modalTitle = ref(null)

    const addFromDialog = () => {
        console.log(response);
        execScenarioDialogVisible.value = false;
        execHermioneDialogVisible.value = false;

        if (currentSelection.value != null) {
            content.value = content.value.substring(0, currentPosition.value) + response.value + content.value.substring(currentPosition.value + currentSelection.value.length);
        } else {
            content.value = content.value.substring(0, currentPosition.value) + response.value + content.value.substring(currentPosition.value);
        }
    }
    
    const onRightClick = (event) => {
        if(currentSelection.value && currentSelection.value.length > 0) {
            items.value=[
                {label: 'Summarize',icon: 'pi pi-language', command:()=>openEditorAssistant(currentSelection.value, "summarize")},
                {label: 'Rewrite', icon: 'pi pi-language', command:()=>openEditorAssistant(currentSelection.value, "rewrite")}
            ]
        }else {
            items.value=[
                {  label: 'Ask Hermione', icon: 'pi pi-language', command:()=>openAskDialog()  },
                {  separator: true},
                { label: 'Execute Scenario', icon: 'pi pi-volume-up',items: scenarioMenuItems}
            ]
        }
        menu.value.show(event);
    };
/*
    const onSelectionChange = (event) => {
        console.log("Testo selezionato", event)
        if(event.range.length === 0){
            currentSelection.value = null;
        } else{
            currentSelection.value = event.textValue;
        }
        currentPosition.value = event.range.index;
    };
*/
    const onSelectionChange = (event) => {
      const { range, textValue } = event;
        console.log(range, textValue)

      if (range && textValue && range.length != 0) {
        const start = range.index
        const end = range.index + range.length

        if (start != null && end != null && start <= end) {        
            currentSelection.value = textValue.substring(start, end);
            console.log(currentSelection.value)
        } else {
          currentSelection.value = null
        }
        currentPosition.value = event.range.index;

        console.log("Testo selezionato", currentSelection.value)
      }
    };

    const scenarioMenuItems = computed(() => { 
        const scenario_items = [];
        for (let i = 0; i < scenarios.value.length; i++) {
            scenario_items.push({
                label: scenarios.value[i].name,
                icon: 'pi pi-file',
                command: () => {
                    executeScenario(scenarios.value[i]);
                }
            });
        }
        return scenario_items;
    });


    const executeScenario = (scenario) => {
        console.log(scenario.id);
        execScenarioDialogVisible.value = true;
        execScenario.value = scenario;
    }

    const openAskDialog = () => {
        execHermioneDialogVisible.value = true;
        askDialog.value = true
        dataLoaded.value = false
        modalTitle.value = "Ask Hermione"
        userQuestion.value = ''
    }

    const openEditorAssistant = (text, action) => {
        execHermioneDialogVisible.value=true
        modalTitle.value = "Editor Assistant"
        askDialog.value = false 
        loadingData.value = true
        dataLoaded.value = false

        if (action === "rewrite") {
            rephraseText(text)
        } else {
            summarizeText(text)
        }
    }

    const rephraseText = (text) => {
        const input = {
            input: text
        }
        console.log("INPUT: ", input);

        axios.post("/rephrase", input).then(resp => {
            console.log("RESPONSE: ", resp.data);
            response.value = resp.data.stringOutput
            loadingData.value = false
            dataLoaded.value = true
        })
        .catch(error => {
            console.error('Error during the request:', error);
        });
    };

    const summarizeText = (text) => {
        const input = {
            input: text
        }
        console.log("INPUT: ", input);

        axios.post("/summarize", input).then(resp => {
            console.log("RESPONSE: ", resp.data);
            response.value = resp.data.stringOutput
            loadingData.value = false
            dataLoaded.value = true
        })
        .catch(error => {
            console.error('Error during the request:', error);
        });
    };

    const askHermione = () => {
        const input = {
            input: userQuestion.value
        }
        console.log("INPUT: ", input);

        loadingData.value = true
        
        axios.post("/askHermione", input).then(resp => {
            console.log("RESPONSE: ", resp.data);
            response.value = resp.data.stringOutput
            loadingData.value = false
            dataLoaded.value = true
            askDialog.value = false
        })
        .catch(error => {
            console.error('Error during the request:', error);
        });
    };

    onMounted(() => {
        ScenarioService.getScenarios().then(resp=>{
            scenarios.value = resp.data
        })
    });
</script>

<style scoped>


</style>