import { defineStore } from 'pinia';
import { computed, ref } from 'vue';
import { ScenarioExecutionService } from '../service/ScenarioExecutionService';
import { ScenarioService } from '../service/ScenarioService';
import { LoadingStore } from './LoadingStore';

export const ScenarioExecutionStore = defineStore('scenario_execution_store', () => {
    const lstScenarioExecution = ref([]);
    const selectedExecScenario = ref(null);
    const currentScenario = ref({});
    const currentExecution = ref(null);
    const executionProgress = ref(null);
    const loadingStore = LoadingStore();

    const totalRecords = ref(0); // Numero totale di record
    const currentPage = ref(0); // Pagina corrente
    const pageSize = ref(10); // Numero di record per pagina
    const filters = ref({}); // Oggetto per memorizzare i filtri

    // Funzione per recuperare le esecuzioni con filtri e paginazione
    async function fetchScenariosExecution(page = 0, size = 10, filters, sortField, sortOrder) {
        loadingStore.scenario_loading = true;
        try {
            console.log('Fetching executions with filters:', page, size, filters, sortField, sortOrder);
            const resp = await ScenarioExecutionService.getExecScenariosByUser(page, size, filters, sortField, sortOrder);
            lstScenarioExecution.value = resp.data.content;
            totalRecords.value = resp.data.totalElements;
            currentPage.value = page;
            pageSize.value = size;
        } catch (error) {
            console.error('Error fetching executions:', error);
        } finally {
            loadingStore.scenario_loading = false;
        }
    }

    // Funzione per recuperare un singolo scenario
    async function fetchScenario(id) {
        try {
            const response = await ScenarioService.getScenarioById(id);
            currentScenario.value = response.data;
            return response.data;
        } catch (error) {
            console.error('Error fetching scenario:', error);
            throw error;
        }
    }

    // Funzione per eseguire uno scenario
    async function executeScenario(data) {
        try {
            const response = await ScenarioService.executeScenarioAsync(data);
            currentExecution.value = response.data;
            return response.data;
        } catch (error) {
            console.error('Error executing scenario:', error);
            throw error;
        }
    }

    // Funzione per recuperare i dettagli di esecuzione
    async function getScenarioExecution(execId) {
        try {
            const response = await ScenarioService.getScenarioExecution(execId);
            return response.data;
        } catch (error) {
            console.error('Error getting scenario execution:', error);
            throw error;
        }
    }

    // Funzione per recuperare il progresso di esecuzione
    async function getExecutionProgress(execId) {
        try {
            const response = await ScenarioService.getExecutionProgress(execId);
            executionProgress.value = response.data;
            return response.data;
        } catch (error) {
            console.error('Error getting execution progress:', error);
            throw error;
        }
    }

    async function downloadFile(filePath, executionId) {
        loadingStore.scenario_loading = true;
        try {
            const response = await ScenarioExecutionService.downloadFile(filePath, executionId);

            // Crea un URL per il blob e avvia il download
            const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement('a');
            link.href = url;

            // Estrae il nome del file dal filePath o usa un nome di default
            const fileName = filePath.split('/').pop() || `file_${executionId}`;
            link.setAttribute('download', fileName);

            document.body.appendChild(link);
            link.click();

            // Cleanup
            link.remove();
            window.URL.revokeObjectURL(url);

            return response;
        } catch (error) {
            console.error('Error downloading file:', error);
            throw error;
        } finally {
            loadingStore.scenario_loading = false;
        }
    }

    const scenariosExecution = computed(() => {
        return lstScenarioExecution.value;
    });

    const getSelectedExecScenario = computed(() => {
        return selectedExecScenario.value;
    });

    const getCurrentPage = computed(() => {
        return currentPage.value;
    });

    const getPageSize = computed(() => {
        return pageSize.value;
    });

    const getTotalRecords = computed(() => {
        return totalRecords.value;
    });

    const getCurrentScenario = computed(() => {
        return currentScenario.value;
    });

    const getCurrentExecution = computed(() => {
        return currentExecution.value;
    });

    const getExecutionProgressData = computed(() => {
        return executionProgress.value;
    });

    const setSelectedExecScenario = (execScenario) => {
        selectedExecScenario.value = execScenario;
    };

    // Funzione per aggiornare i filtri
    const updateFilters = (newFilters) => {
        console.log('New filters:', newFilters);
        filters.value = newFilters;
        filters.value = encodeURIComponent(JSON.stringify(newFilters));
        fetchScenariosExecution(currentPage.value, pageSize.value, filters.value); // Ricarica con i nuovi filtri
    };

    // Funzione per resettare lo store
    const resetStore = () => {
        lstScenarioExecution.value = [];
        selectedExecScenario.value = null;
        currentScenario.value = {};
        currentExecution.value = null;
        executionProgress.value = null;
        totalRecords.value = 0;
        currentPage.value = 0;
        pageSize.value = 10;
        filters.value = {};
    };

    return {
        getCurrentPage,
        getPageSize,
        getTotalRecords,
        getCurrentScenario,
        getCurrentExecution,
        getExecutionProgressData,
        fetchScenariosExecution,
        fetchScenario,
        executeScenario,
        getScenarioExecution,
        getExecutionProgress,
        downloadFile,
        selectedExecScenario,
        lstScenarioExecution,
        scenariosExecution,
        getSelectedExecScenario,
        setSelectedExecScenario,
        updateFilters,
        filters,
        resetStore
    };
});
