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

export const useDashboardStore = defineStore('dashboard', {
    state: () => ({
        stats: null,
        pullInterval: 3000,
        pullTimer: null,
    }),
    getters: {
        completed(state) {
            if (state.stats)
                return state.stats.completed;

            return null;
        },
        running(state) {
            if (state.stats)
                return state.stats.running;

            return null;
        },
        drafts(state) {
            if (state.stats)
                return state.stats.drafts;

            return null;
        },
        failed(state) {
            if (state.stats)
                return state.stats.failed;

            return null;
        }
    },
    actions: {
        async load() {
            const url = `${config.backendUrl}/dashboard`;
            const resp = await performRequest(this, 'GET', url, null);

            if(this.stats?.running && this.stats.running > 0 && resp.data.running === 0) {
                useNotificationStore().addNotification({
                    title: 'Calculation',
                    message: 'All your calculations have been completed.',
                    variant: 'info',
                    icon: 'calculator',
                })
            }

            this.stats = resp.data;
        },
        startPulling() {
            if (this.pullTimer) return

            this.pullTimer = setTimeout(async () => {
                await this.pull()
            }, this.pullInterval)
        },
        stopPulling() {
            if (this.pullTimer) {
                clearTimeout(this.pullTimer)
                this.pullTimer = null
            }
        },
        async pull() {
            await this.load();
            this.stopPulling();
            this.startPulling();
        }
    }

});