import classNames from 'classnames';
import _ from 'lodash';
import { Component, PropTypes } from 'react';
import ReactDOM from 'react-dom';

const propTypes = {
    children: PropTypes.node.isRequired,
    containerSelector: PropTypes.string, // eg. we need to render into the '.aui-inline-dialog-contents' of an aui-inline-dialog
    id: PropTypes.string,
    markup: PropTypes.string.isRequired,
    wrapperClass: PropTypes.string, // the wrapper class can be helpful when a very specific CSS selector is required for AUI
};

class AUIComponent extends Component {

    componentDidMount() {
        const node = ReactDOM.findDOMNode(this);
        node.innerHTML = this.props.markup;
        node.firstChild.id = this.props.id;
        _.defer(() => this.updateContent());
    }

    componentDidUpdate() {
        this.updateContent();
    }

    componentWillUnmount() {
        ReactDOM.unmountComponentAtNode(this.getContainer());
        // if there is an ID also try to remove the component with that ID.
        // This should take care of any container elements that AUI has moved.
        if (this.props.id) {
            const el = document.querySelector(`#${this.props.id}`);
            if (el) {
                el.parentNode.removeChild(el); // update when we drop IE11 support
            }
        }
    }

    getContainer() {
        if (this._container) {
            return this._container;
        }
        const containerSelector = this.props.containerSelector || `#${this.props.id}`;
        this._container = document.querySelector(containerSelector);
        return this._container;
    }

    updateContent() {
        const content = <div className={classNames(this.props.wrapperClass)}>{this.props.children}</div>;
        if (this.getContainer()) {
            ReactDOM.render(content, this.getContainer());
        }
    }

    render() {
        return <div />;
    }
}

AUIComponent.propTypes = propTypes;

export default AUIComponent;
