import React from 'react'
import PropTypes from 'prop-types'
import alerts from 'containers/alerts'
import Debug from 'common-fe/utils/debug'
import alertTypes from './alert-types'

class AlertManager extends React.PureComponent {
    static alertFor = (type) => alerts[type] || null

    dismissAlert = () => {
        const {
            alert: {onDismiss},
            hideAlert,
        } = this.props
        hideAlert && hideAlert()
        onDismiss && onDismiss()

        return Promise.resolve()
    }

    render() {
        const {
            alert: {isShowing, type, ...customProps},
        } = this.props
        const alert = AlertManager.alertFor(type)

        if (!alert) {
            // DEFAULT is the default alert type initialized in the reducer and
            // is intentionally null.
            // We want to warn ourselves when the alert manager isn't able to
            // resolve a alert for the specified type in every other case.
            type !== alertTypes.DEFAULT &&
                Debug.warn(`WARN: No alert found for type ${type}.`)
            return null
        }

        const {template: Alert, ...alertProps} = alert

        return (
            <Alert
                {...alertProps}
                {...customProps}
                isShowing={isShowing}
                onDismiss={this.dismissAlert}
            />
        )
    }
}

AlertManager.propTypes = {
    alert: PropTypes.shape({
        isShowing: PropTypes.bool.isRequired,
        template: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
        type: PropTypes.string,
        onDismiss: PropTypes.func,
    }).isRequired,
    hideAlert: PropTypes.func,
}

export default AlertManager
