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

export class NotificationDispatcher extends React.Component<any, any> {
    static childContextTypes = {
        isTopFixedNotification: PropTypes.bool
    };

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

    getChildContext() {
        return {
            isTopFixedNotification: true
        };
    }

    showNotification(element) {
        let key = Date.now();
        let notification = React.cloneElement(element, {
            key,
            onClose: () => {
                this.onNotificationClose(key);
                if (element.props.onClose) {
                    element.props.onClose();
                }
            }
        });
        return new Promise(resolve => {
            let stack = [{notification, key}, ...this.state.stack];
            this.setState({stack}, resolve);
        });
    }

    onNotificationClose(key) {
        let index = _.findIndex(this.state.stack, {key});
        if (index !== -1) {
            this.setState(state => {
                let stack = [...state.stack];
                stack.splice(index, 1);
                return {stack};
            });
        }
    }

    render() {
        return <div>{this.state.stack.map(({notification}) => notification)}</div>;
    }
}
