import React from 'react'
import {ConsentEvent} from '@signatu/consent'
import {Popup} from '../components/consentPopup'

/** Create a conditional popup when there is no existing consent event */

/**
 * Props: autoClose: boolean - close when the user has given or revoked consent
 */

 export const makeConsentCondPopup = (Component: React.ComponentType<any>, defaultCloseDelay = 500): React.ComponentType<any>  => class extends React.Component<any> {
    state = {
        show: false, 
    }

    onLoaded = (consent: ConsentEvent) => {
        if ( ! consent ) {
            this.setState({show: true})
        }
        this.props.onLoaded && this.props.onLoaded(consent)
    }


    onAction = (consent: ConsentEvent) => {
        this.props.onAction && this.props.onAction(consent)

        if (this.props.autoClose) {
            this.close()
        }
    }

    close = () => {
        setTimeout(() => this.setState({show: false}), this.props.closeDelay || defaultCloseDelay)
    }

    render() {
        /** We need to pre-load the component, so we cannot have it behind a conditional */
        return <Popup 
            preload={true}
            show={this.state.show}
            contentStyle={{maxWidth: "600px", overflow: "auto"}}
            onClose={this.close}>
                 <Component {...this.props} onLoaded={this.onLoaded} onAction={this.onAction}/>
        </Popup>
    }
}
