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

type NavDropdownProps = {
    children: React.ReactNode;
    testAutomationId?: string;
} & React.HTMLProps<NavDropdown>;

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

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

    componentDidMount() {
        this.addAccessibility();
    }

    componentDidUpdate() {
        this.addAccessibility();
    }

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

        let node = ReactDOM.findDOMNode(this) as any;
        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 as any}>
                {children}
            </ReactBootstrapNavDropdown>
        );
    }
}
