import { sanitizeHeaderMessageId } from '../../core-utils.mjs.js';
import { createLogger } from '../../logger.mjs.js';

const logger = createLogger('modules/store/selectors');

export const selectMindrs = (/** @type {MailmindrState} */ state) =>
    state.mindrs || [];

export const selectMindrByGuid = (
    /** @type {MailmindrState} */ state,
    guid
) => {
    const mindrs = selectMindrs(state);
    const result = (mindrs || []).find(item => item.guid === guid);

    return result;
};

export const selectMindrByHeaderMessageId = (
    /** @type {MailmindrState} */ state,
    headerMessageId
) => {
    const mindrs = selectMindrs(state);
    const result = (mindrs || []).find(
        item =>
            sanitizeHeaderMessageId(item.headerMessageId) ===
            sanitizeHeaderMessageId(headerMessageId)
    );

    return result;
};

export const selectOpenDialogs = (/** @type {MailmindrState} */ state) =>
    state.openDialogs || [];

export const selectDialogForType = (
    /** @type {MailmindrState} */ state,
    dialogType
) => {
    const openDialogs = selectOpenDialogs(state);
    logger.log(selectDialogForType.name, { state, openDialogs });
    return openDialogs.find(dialog => dialog.dialogType === dialogType);
};

export const selectSettings = (/** @type {MailmindrState} */ state) =>
    state.settings;

export const selectPresets = (/** @type {MailmindrState} */ state) =>
    state.presets;

export const selectOpenConnections = (/** @type {MailmindrState} */ state) =>
    state.openConnections || [];

export const selectDrafts = (/** @type {MailmindrState} */ state) => {
    return state.__drafts || [];
};

export const selectDraftForSenderTabOrNull = (
    /** @type {MailmindrState} */ state,
    /** @type {MindrDraft['sender']} */ sender
) => {
    const drafts = selectDrafts(state);
    const result = drafts.find(
        ({ sender: { id, windowId } }) =>
            id === sender.id && windowId === sender.windowId
    );
    return result || null;
};
