import {defineStore} from 'pinia'
import {config} from '@/config'
import {useNotificationStore} from "@/store/notification.js";
import performRequest, {performDownload, performUpload} from "@/backend.js";

export const useBulkOperationStore = defineStore('bulkOperation', {
    state() {
        return {
            bulkOperations: [],
            loading: false,
            updateInterval: 3000,
            updateTimer: null
        }
    },
    getters: {
        getBulkOperations(state) {
            return state.bulkOperations;
        },
        isLoading(state) {
            return state.loading;
        }
    },
    actions: {
        async scheduleDownload(dataset, period) {
            const url = `${config.backendUrl}/bulk/download/${dataset}/${period === null ? '' : period}`;
            await performRequest(this, 'GET', url, null, false);
            await this.updateStatus();
            this.startTimer();
        },
        async scheduleUpload(dataset, file) {
            const url = `${config.backendUrl}/bulk/upload/${dataset}/`
            await performUpload(url, file, false);
            await this.updateStatus();
            this.startTimer();
        },
        async timerMethod() {
            await this.updateStatus();
            const restart = this.restartNeeded();

            this.stopTimer();

            if(!restart)
                useNotificationStore().addNotification({
                    title: 'Bulk operation',
                    message: 'All your bulk operations have been completed.',
                    type: 'success',
                    icon: 'stack',
                })

            if(restart) {
                this.startTimer();
            }

        },
        async manageStatus() {
            await this.updateStatus();
            if(this.restartNeeded())
                this.startTimer();
        },
        async updateStatus() {
            this.loading = true;

            const url = `${config.backendUrl}/bulk/status`;
            const {data: data, headers: headers} = await performRequest(this, "GET", url, null, true);
            this.bulkOperations = data;

            this.loading = false;
        },
        restartNeeded() {
            if((this.updateTimer === null) && this.bulkOperations.some(op => (op.state === 'SCHEDULED' || op.state === 'PROCESSING')))
                return true;

            if (!this.bulkOperations.some(op => (op.state === 'SCHEDULED' || op.state === 'PROCESSING')))
                return false;

            return true;
        },
        async downloadBulkFile(id) {
            const op = this.bulkOperations.find(op => op.id === id);
            if ((op ?? null) === null) return;

            const fileName = this.getFileName(op.file_type.toLowerCase(), op.processing_type.toLowerCase());
            const url = `${config.backendUrl}/bulk/file/${id}`;

            await performDownload(url, fileName);
        },
        getFileName(dataset, type) {
            return `lcc_export_${type}_${dataset}.xlsx`;
        },
        startTimer() {
            if (this.updateTimer) return

            this.updateTimer = setTimeout(async () => {
                await this.timerMethod()
            }, this.updateInterval)
        },
        stopTimer() {
            if (this.updateTimer) {
                clearTimeout(this.updateTimer)
                this.updateTimer = null
            }
        },
    }
});