let clearMessageTimeoutId;

export function playMessage(messageText, politenessSetting = 'assertive') {
    const ariaLiveRegionId = 'aria-live-region';

    function createAriaLiveRegion(id) {
        let ariaLiveRegionContainer = document.createElement('div');
        let ariaLiveRegion = document.createElement('div');

        ariaLiveRegionContainer.className = 'bootstrap-rc';
        ariaLiveRegion.id = id;
        ariaLiveRegion.className = 'sr-only';
        ariaLiveRegion.setAttribute('aria-live', 'assertive');

        ariaLiveRegionContainer.appendChild(ariaLiveRegion);

        document.body.appendChild(ariaLiveRegionContainer);

        return ariaLiveRegion;
    }

    if (!messageText) {
        return;
    }

    if (clearMessageTimeoutId) {
        clearTimeout(clearMessageTimeoutId);
    }

    let ariaLiveRegion = document.getElementById(ariaLiveRegionId);
    if (!ariaLiveRegion) {
        ariaLiveRegion = createAriaLiveRegion(ariaLiveRegionId);
    }

    const currentPolitenessSetting = ariaLiveRegion.getAttribute('aria-live');
    if (politenessSetting !== currentPolitenessSetting) {
        ariaLiveRegion.setAttribute('aria-live', politenessSetting);
    }

    ariaLiveRegion.innerHTML = messageText;

    clearMessageTimeoutId = setTimeout(() => {
        ariaLiveRegion.innerHTML = '';
    }, 500);
}
