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

import Wrapper from './Wrapper';

export default class RenderInBody extends React.Component{
    static contextTypes = {
        router: PropTypes.object,
        location: PropTypes.object,
        body: PropTypes.object,
        getHeader: PropTypes.func,
        showPopup: PropTypes.func,
        hidePopup: PropTypes.func
    }

    componentDidMount(){
        if(this.props.ix) {
            this.popup = document.getElementById(this.props.ix);
        }
        if (!this.popup) {
            this.popup = document.createElement('div');
            this.popup.id = this.props.ix || '';
            this.popup.className = this.props.clsName || this.props.className || 'in-body';
            var body = this.getBody();
            body && body.appendChild(this.popup);
        }
        this._renderLayer();
    }
    componentDidUpdate() {
        this._renderLayer();
    }
    getBody(){
        return this.props.parent || this.context.body || document.getElementsByTagName('body')[0];
    }
    componentWillUnmount(){
        if(this.popup) {
            ReactDOM.unmountComponentAtNode(this.popup);
            var body = this.getBody();
            body && body.removeChild(this.popup);
        }
    }
    _renderLayer(){
        let props = this.props;
        ReactDOM.render(<Wrapper
            router={this.context.router || props.router}
            location = {this.context.location || props.location}
            body = {this.context.body || props.body}
            getHeader = {this.context.getHeader || props.getHeader}
            showPopup = {this.context.showPopup || props.showPopup}
            hidePopup = {this.context.hidePopup || props.hidePopup}
        >{this.props.children}</Wrapper>, this.popup);
    }
    render() {
        return <div />;
    }
}
