import { isExecuted, showReminderForMindr } from '../../core-utils.mjs.js';
import { createLogger } from '../../logger.mjs.js';
import { executeMindr } from './executeMindr.mjs.js';
import { showMindrAlert } from './index.mjs.js';

const logger = createLogger('modules/store/actions/heartBeat');

export const heartBeatEx = () => async (dispatch, getState) => {
    const { overdue, active, __inExecution } = getState();
    const overdueNotExecuted = overdue.filter(item => !item.isExecuted);

    logger.log(`heartBeatEx -- `, { overdue, active, overdueNotExecuted });

    if (Array.isArray(__inExecution) && __inExecution.length > 0) {
        logger.warn(
            `Mindr is executing (${__inExecution.length} in total), skipping further executions`,
            { overdue, active, __inExecution }
        );
        return;
    }

    logger.log(`overdueNotExecuted: `, overdueNotExecuted);
    for (let mindr of overdueNotExecuted) {
        dispatch(executeMindr(mindr));
    }

    // 
    // 
    const overdueAndUnexecuted = overdue.filter(
        mindr => !isExecuted(mindr) && showReminderForMindr(mindr)
    );

    const activeMindrs = active.filter(showReminderForMindr);

    if (overdueAndUnexecuted.length > 0 || activeMindrs.length > 0) {
        logger.info(`heartbeat: show dialog with mindrs `, {
            overdueAndUnexecuted,
            active: activeMindrs
        });
        dispatch(
            showMindrAlert({
                overdue: overdueAndUnexecuted,
                active: activeMindrs
            })
        );
    } else {
        logger.log('No reason to show a dialog', { overdueAndUnexecuted });
    }
};
