import React from 'react';
import PropTypes from 'prop-types';

export class PopupDispatcher extends React.Component<any, any> {
    static propTypes = {
        popupContext: PropTypes.object
    };

    static defaultProps = {
        popupContext: null
    };

    // TODO (UIA-70822) for now it is hardcoded since childContextTypes is mandatory, redo with new context API when React is updated
    static childContextTypes = {
        store: PropTypes.object // Redux store
    };

    constructor(props, context) {
        super(props, context);
        this.state = {
            stack: []
        };
    }

    getChildContext() {
        const {popupContext} = this.props;

        if (!popupContext) {
            return {};
        }

        return {
            store: popupContext.store || null
        };
    }

    showPopup(element) {
        if (element.props.onHide) {
            throw new Error('showPopup do not support onHide property of Popup');
        }

        let popup: any = React.cloneElement(element, {
            onHide: () => {
                let stack = this.state.stack;
                let index = stack.indexOf(popup);

                if (index !== -1) {
                    stack.splice(index, 1);

                    this.setState({stack});
                }
            }
        });

        return new Promise(resolve => {
            if (popup.props.stackable) {
                this.setState({stack: [...this.state.stack, popup]}, resolve);
            } else {
                this.setState({stack: [popup]}, resolve);
            }
        });
    }

    closePopup() {
        if (this.state.stack.length) {
            this.state.stack[this.state.stack.length - 1].props.onHide();
        }
    }

    render() {
        return <div>{this.state.stack.map((popup, key) => React.cloneElement(popup, {key}))}</div>;
    }
}
