import { usePrevious } from '@planview/pv-utilities'
import * as React from 'react'
import { defineMessages, useIntl } from 'react-intl'
import { useGridLiveRegion } from '../context/grid-live-region-context'

const messages = defineMessages({
    loading: {
        id: 'pvds.grid.aria.loading',
        defaultMessage: 'Loading data. Please wait',
        description: 'Screen reader announcement when in loading state',
    },
    loadingComplete: {
        id: 'pvds.grid.aria.loadingComplete',
        defaultMessage: 'Loading complete',
        description:
            'Screen reader announcement for the loading state when grid has finished loading',
    },
})

const CALL_OUT_THRESHOLD = 500 //ms to wait until calling out loading state.

/**
 * @method useAriaLoadingMessage: hook to set content of aria-live region to call out loading state when appropriate
 * @returns message [string]: loading state string to be put in aria live region
 */
export const useAriaLoadingMessage = (loading: boolean) => {
    const intl = useIntl()
    const previousLoading = usePrevious(loading)
    const { setAnnouncement } = useGridLiveRegion()

    React.useEffect(() => {
        let setMessageTimer = 0
        if (loading) {
            setMessageTimer = window.setTimeout(() => {
                setAnnouncement(intl.formatMessage(messages.loading))
            }, CALL_OUT_THRESHOLD)
        } else if (previousLoading) {
            setAnnouncement(intl.formatMessage(messages.loadingComplete))
        }
        return () => {
            if (setMessageTimer) {
                window.clearTimeout(setMessageTimer)
                setMessageTimer = 0
            }
        }
    }, [intl, loading, previousLoading, setAnnouncement])
}
