import _ from "lodash";

export default {
    state: {
        visitorsCount: null,
        jobCount: null,
    },
    getters: {
        getVisitorsStats(state) {
            return state.visitorsCount;
        },
        getJobStats(state) {
            return state.jobCount;
        }
    },
    mutations: {
        setStats(state, { visitorsCount, jobCount }) {
            state.visitorsCount = visitorsCount ?? state.visitorsCount;
            state.jobCount = jobCount ?? state.jobCount;
        },

    },
    actions: {
        async fetchStats(context) {
            let jobsPromise = context.getters.getApi.get(`/stats/jobs`);
            let visitorsPromise = context.getters.getApi.get(`/stats/visitors`);
            let statsPromise = Promise.allSettled([jobsPromise, visitorsPromise]);


            jobsPromise.then((jobs) => context.commit("setStats", { jobCount: jobs.data.jobs })
            ).catch(err => {
                console.error(err);
                console.warn("Something went wrong fetching job stats, ignoring")
            });


            visitorsPromise.then((visitors) => context.commit("setStats", { visitorsCount: visitors.data.visitors })
            ).catch(err => {
                console.error(err);
                console.warn("Something went wrong fetching visitor stats, ignoring")
            });




            context.dispatch("addAwaitable", {
                id: _.uniqueId("awaiting"),
                promise: statsPromise,
                description: "FetchingUserStats"
            });

        }


    }
}