import React from 'react'
import PropTypes from 'prop-types'
import banners from 'containers/banners'
import Debug from 'common-fe/utils/debug'
import bannerTypes from './banner-types'

class BannerManager extends React.PureComponent {
    static bannerFor = (type) => banners[type] || null

    dismissModal = () => {
        const {
            banner: {onDismiss},
            hideBanner,
        } = this.props
        hideBanner && hideBanner()
        onDismiss && onDismiss()

        return Promise.resolve()
    }

    render() {
        const {
            banner: {isShowing, type, ...customProps},
        } = this.props
        const banner = BannerManager.bannerFor(type)

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

        const {template: Banner, templateProps, ...bannerProps} = banner

        return (
            <Banner
                {...customProps}
                {...bannerProps}
                isShowing={isShowing}
                templateProps={templateProps}
                onDismiss={this.dismissModal}
            />
        )
    }
}

BannerManager.propTypes = {
    banner: PropTypes.shape({
        isShowing: PropTypes.bool.isRequired,
        type: PropTypes.string.isRequired,
        template: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
        templateProps: PropTypes.object,
        onDismiss: PropTypes.func,
    }).isRequired,
    hideBanner: PropTypes.func,
}

export default BannerManager
