
const state = {
    pollingJobResults: []
};

export default {
    state,
    getters: {
        getJob: (state) => (name) => {
            return state.pollingJobResults.find(item => item.name === name);;
        },
        getJobAttemptCount: (state) => (name) => {
            let job = state.pollingJobResults.find(item => item.name === name);
            return job ? job.pollingAttemptsCount : 0;
        },
    },
    mutations: {
        ADD_POLLING_JOB_RESULT(state, {jobId, name, pollingAttemptsCount, isPolling, isFetchingResult, maxAttempts, pollJobResult, interval}) {
            let intervalId = setInterval(() => {
                if (pollJobResult) {
                    pollJobResult(state);
                }
            }, interval);
            state.pollingJobResults.push({ jobId, name, pollingAttemptsCount, isPolling, isFetchingResult, maxAttempts, intervalId});
        },
        UPDATE_POLLING_JOB_RESULT(state, { jobId, pollingAttemptsCount, isPolling, isFetchingResult, isLastAttempt}) {
            const index = state.pollingJobResults.findIndex(s => s.jobId === jobId);
            if (index !== -1) {
              const updatedPollingJobResults = [...state.pollingJobResults];
              updatedPollingJobResults[index] = { ...updatedPollingJobResults[index],
                jobId,
                pollingAttemptsCount: pollingAttemptsCount !== undefined ? pollingAttemptsCount : updatedPollingJobResults[index].pollingAttemptsCount,
                isPolling: isPolling !== undefined ? isPolling : updatedPollingJobResults[index].isPolling,
                isFetchingResult: isFetchingResult !== undefined ? isFetchingResult : updatedPollingJobResults[index].isFetchingResult,
                isLastAttempt: isLastAttempt !== undefined ? isLastAttempt : updatedPollingJobResults[index].isLastAttempt,
              };
              state.pollingJobResults = updatedPollingJobResults;
            }
        },
        REMOVE_POLLING_JOB_RESULT_BY_JOBID(state, jobId) {
            const index = state.pollingJobResults.findIndex(s => s.jobId === jobId);
            if (index !== -1) {
              clearInterval(state.pollingJobResults[index].intervalId);
              state.pollingJobResults.splice(index, 1);
            }
        },
        // REMOVE_POLLING_JOB_RESULT_BY_JOBID_2(state, jobId) {
        //     const index = state.pollingJobResults.findIndex(s => s.jobId === jobId);
        //     if (index !== -1) {
        //       clearInterval(state.pollingJobResults[index].intervalId);
        //       //state.pollingJobResults.splice(index, 1);
        //     }
        // },
        REMOVE_POLLING_JOB_RESULT_BY_NAME(state, name) {
            const index = state.pollingJobResults.findIndex(s => s.name === name);
            if (index !== -1) {
              clearInterval(state.pollingJobResults[index].intervalId);
              state.pollingJobResults.splice(index, 1);
            }
        },
    },
    actions: {
        submitJobRequest({ dispatch }, { url, name }){
            dispatch('crudRequestV2', {
                endpoint: url,
                method: 'get',

            }).then(response => {
                let success = response.ok;
                response.json().then(response => {
                    if(!success){return;}
                    let jobId = response.payload.data.job_id;
                    if(jobId){
                        let pollingAttemptsCount = 0;
                        dispatch('startPolling', { jobId, name, pollingAttemptsCount });
                    }
                });
            })
        },

        stopPollingJobResultByJobId({ commit }, { jobId }){
            commit('REMOVE_POLLING_JOB_RESULT_BY_JOBID', jobId);
        },

        stopPollingJobResultByName({ commit }, { name }){
            commit('REMOVE_POLLING_JOB_RESULT_BY_NAME', name);
        },

        startPolling({ state, commit, dispatch }, { jobId, name, pollingAttemptsCount, maxAttempts = 8}) {
            let interval = 10000;

            // console.log(`startPolling jobId: ${jobId}, pollingAttemptsCount: ${pollingAttemptsCount}, name: ${name}`);

            const pollJobResult = (state) => {
                //console.log(`MONITOR state ${JSON.stringify(state)}`);
                const index = state.pollingJobResults.findIndex(s => s.jobId === jobId);
                if (index !== -1) {
                    pollingAttemptsCount = state.pollingJobResults[index].pollingAttemptsCount;
                    if (state.pollingJobResults[index].isPolling || state.pollingJobResults[index].isFetchingResult) {
                        return;
                    }
                }
                else{
                    return;
                }

                pollingAttemptsCount++;
                if(pollingAttemptsCount === 1){
                    commit("REMOVE_POLLING_JOB_RESULT_BY_JOBID", jobId );
                    commit("ADD_POLLING_JOB_RESULT", { jobId, name, pollingAttemptsCount, isPolling: false, isFetchingResult: false, maxAttempts, pollJobResult, interval: 5000});
                }

                if (pollingAttemptsCount > maxAttempts) {
                    //console.log(`Reached maximum attempts (${maxAttempts}). Polling stopped.`);
                    commit("REMOVE_POLLING_JOB_RESULT_BY_JOBID", jobId );
                    return;
                }

                if(pollingAttemptsCount === maxAttempts){
                    commit('UPDATE_POLLING_JOB_RESULT', { jobId, pollingAttemptsCount, isPolling: true, isFetchingResult: false, isLastAttempt: true });
                }
                else{
                    commit('UPDATE_POLLING_JOB_RESULT',  { jobId, pollingAttemptsCount, isPolling: true, isFetchingResult: false, isLastAttempt: false});
                }
            }
            commit("ADD_POLLING_JOB_RESULT", { jobId, name, pollingAttemptsCount, isPolling: false, isFetchingResult: false, maxAttempts, pollJobResult, interval});

        },

        updatePollingJobResultByJobId({ commit }, { jobId, isPolling, isFetchingResult }){
            commit('UPDATE_POLLING_JOB_RESULT', { jobId, isPolling, isFetchingResult });
        }
    }
}
