import * as React from 'react'

export abstract class OpenableComponent<T> extends React.Component<T, any> {

    public container: any

    constructor(props: any) {
        super(props)
        this.isActive = this.isActive.bind(this)
        this.handleClose = this.handleClose.bind(this)
    }
    public componentDidMount() {
        document.addEventListener('click', this.handleClickAway);
    }

    public componentWillUnmount() {
        document.removeEventListener('click', this.handleClickAway);
    }

    public setContainerRef = (e: any) => this.container = e

    public handleClickAway = (event: MouseEvent) => {
        // clicking away from the component should close it
        // console.log('HANDLE CLICK  AWAY', this.props, this.container)

        if (this.isActive() && !this.container.contains(event.target as any)) {
            this.handleClose()
        }
    }

    public abstract isActive(): boolean

    public abstract handleClose(): any
}
