import {
    createMailmindrId,
    sendConnectionMessageEx
} from '../../core-utils.mjs.js';
import { createLogger } from '../../logger.mjs.js';
import {
    selectDialogForType,
    selectOpenConnections
} from '../selectors/index.mjs.js';
import { closeDialog, openDialog } from './actions.mjs.js';

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

export const showMindrAlert = ({ overdue, active }) => async (
    dispatch,
    getState
) => {
    const dialogType = 'mailmindr:mindr-alert';
    const state = getState();
    const openConnections = selectOpenConnections(state);

    const dialogs = (await messenger.tabs.query({})).filter(tab => {
        if (tab && tab.url) {
            return tab.url.indexOf('/mindr-alert/') > 0;
        }
        return false;
    });
    const alertDialog = dialogs && dialogs.length && dialogs[0];
    const dialog = alertDialog
        ? { details: { id: alertDialog.windowId, tabId: alertDialog.id } }
        : null;

    if (dialog) {
        logger.log('we already have a message dialog', dialog);

        if ((overdue || []).length === 0 && (active || []).length === 0) {
            logger.log(`no overdue or active mindrs → we can close the dialog`);

            // 
            dispatch(closeDialog(dialog.details.id));
            messenger.windows.remove(dialog.details.id);
        } else {
            logger.log(`we have a dialog and send data to it`, {
                overdue,
                active
            });

            // 
            await sendConnectionMessageEx(
                openConnections,
                {
                    overdue,
                    active
                },
                'connection:mindr-alert'
            );
            await messenger.windows.update(dialog.details.id, {
                focused: false,
                drawAttention: true
            });
        }
    } else {
        logger.log(
            'need to open a new dialog with active/overdue mindrs',
            active,
            overdue
        );
        if ((active || []).length === 0 && (overdue || []).length === 0) {
            logger.log('no dialog needed');
            return;
        }
        const dialogId = createMailmindrId('mailmindr:dialog:mindr-alert');

        const parameters = new URLSearchParams();
        parameters.set('dialogId', dialogId);

        const { width: screenWidth, availHeight: screenHeight } = screen;
        const height = 200;
        const width = 400;
        const left = screenWidth - width;
        const top = screenHeight - height;
        const url = `/views/dialogs/mindr-alert/index.html?${parameters}`;
        const details = await messenger.windows.create({
            left,
            top,
            height,
            width,
            url,
            type: 'popup',
            state: 'normal',
            allowScriptsToClose: true
        });

        await messenger.windows.update(details.id, {
            top,
            left,
            width,
            height,
            focused: true,
            drawAttention: true
        });

        dispatch(openDialog(dialogId, dialogType, details));
    }
};
