import { sleep } from '../../../../utils/sleep.js';
const DEFAULT_EDIT_MODE_RETRY_TIMING = {
    retryIntervalMs: 1_000,
    blockingPromptAfterMs: 5_000,
    promptCooldownMs: 5_000
};
const EDIT_MODE_STATUS_MESSAGE = 'Excel is in edit mode - press Enter or Escape in Excel to continue...';
const EDIT_MODE_ABORT_MESSAGE = 'Excel execution aborted while waiting for the user to exit edit mode.';
function throwEditModeAbort() {
    throw new Error(EDIT_MODE_ABORT_MESSAGE);
}
export function getEditModeAbortMessage() {
    return EDIT_MODE_ABORT_MESSAGE;
}
export function isEditModeAbortError(error) {
    return (error instanceof Error &&
        (error.name === 'AbortError' ||
            error.message === 'Aborted' ||
            error.message === EDIT_MODE_ABORT_MESSAGE));
}
export async function resolveEditModeRetry(initialResult, options) {
    let result = initialResult;
    let statusShown = false;
    const timing = {
        ...DEFAULT_EDIT_MODE_RETRY_TIMING,
        ...options.timing
    };
    let nextPromptAt = Date.now() + timing.blockingPromptAfterMs;
    while (result.editMode) {
        if (options.signal?.aborted) {
            throwEditModeAbort();
        }
        if (options.ctx?.hasUI) {
            if (!statusShown) {
                options.ctx.ui.notify(EDIT_MODE_STATUS_MESSAGE, 'warning');
                statusShown = true;
            }
            if (Date.now() >= nextPromptAt) {
                const shouldRetry = await options.ctx.ui.confirm('Excel is still in edit mode', 'Exit edit mode in Excel, then choose Yes to retry. Choose No to abort.', { signal: options.signal });
                if (!shouldRetry) {
                    throwEditModeAbort();
                }
                nextPromptAt = Date.now() + timing.promptCooldownMs;
            }
        }
        try {
            await sleep(timing.retryIntervalMs, options.signal);
        }
        catch {
            throwEditModeAbort();
        }
        result = await options.send();
    }
    return result;
}
//# sourceMappingURL=edit-mode-retry.js.map