import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import ReactBootstrapNavDropdown from 'react-bootstrap/lib/NavDropdown';

export class NavDropdown extends React.Component {
    static propTypes = {
        children: PropTypes.node.isRequired,
        testAutomationId: PropTypes.string,
        tabIndex: PropTypes.number,
        role: PropTypes.string
    };

    static defaultProps = {
        testAutomationId: null,
        tabIndex: 0,
        role: 'menuitem'
    };

    componentDidMount() {
        this.addAccessibility();
    }

    componentDidUpdate() {
        this.addAccessibility();
    }

    addAccessibility() {
        let {tabIndex, role} = this.props;

        let node = ReactDOM.findDOMNode(this);
        node.setAttribute('role', 'presentation');
        node.querySelector('.dropdown-toggle').setAttribute('tabindex', tabIndex);
        node.querySelector('.dropdown-toggle').setAttribute('role', role);
    }

    render() {
        let {tabIndex, children, testAutomationId, ...props} = this.props;

        return (
            <ReactBootstrapNavDropdown data-test-automation-id={testAutomationId} {...props}>
                {children}
            </ReactBootstrapNavDropdown>
        );
    }
}
