import React from 'react';
import ReactDOM from 'react-dom';
import { NavbarButton } from '../navbar-button';
import './navbar-user-button.less';

/**\

    title: NavbarUserButton
    category: component
    description: Button that toggles account dropdown

\**/

class NavbarUserButton extends React.Component {
    state = {
        open: false
    };

    componentDidMount() {
        /* istanbul ignore next */
        this.handleClick = (e) => {
            if (!ReactDOM.findDOMNode(this).contains(e.target)) {
                this.close();
            }
        };

        document.addEventListener('click', this.handleClick, false);
    }

    componentWillUnmount() {
        /* istanbul ignore next */
        document.removeEventListener('click', this.handleClick, false);
    }

    close() {
        this.setState({ open: false });
    }

    toggle(e) {
        /* istanbul ignore next */
        e.preventDefault();

        /* istanbul ignore next */
        this.setState({
            open: !this.state.open
        });
    }

    render() {
        let classer = 'navbar-user-button',
            items;

        if (this.state.open) {
            classer += ' open';
            items = this.props.children;
        }

        return (
            <div className={ classer }>
                <NavbarButton click={ this.toggle.bind(this) } />
                { items }
            </div>
        );
    }
}

export default NavbarUserButton;
