import React, {findDOMNode, Component, cloneElement, PropTypes} from 'react';

import HoverCard from '../HoverCard/HoverCard';

export default class Dropdown extends Component {

  // TODO:
  // - Close on ESC
  // - Close when it's clicked away from

  constructor(props, context) {
    super(props, context);

    this.hide = this.hide.bind(this);
    this.toggleShow = this.toggleShow.bind(this);
    this.handleCloseRequest = this.handleCloseRequest.bind(this);

    this.state = {
      show: false
    };
  }

  hide() {
    this.setState({show: false});
  }

  toggleShow() {
    this.setState(state => ({show: !state.show}));
  }

  handleCloseRequest(e) {
    if (e.keyCode ||
        (e.target && !findDOMNode(this.refs.trigger).contains(e.target))) {
      this.hide();
    }
  }

  render() {
    const {container, placement, children, trigger, datepicker} = this.props;
    const clonedTrigger = cloneElement(trigger, {
      onClick: this.toggleShow,
      ref: 'trigger'
    });

    return (
      <span>
        {this.state.show ?
          <HoverCard container={container}
                     variant={datepicker ? 'datepicker' : 'dropdown'}
                     anchor={this.refs.trigger}
                     anchorPadding={20}
                     placement={placement}
                     ref="hovercard"
                     onRequestClose={this.handleCloseRequest}
                     escListen={true}
                     caret={true}>
            {children}
          </HoverCard>
          : null
        }

        {clonedTrigger}
      </span>
    );
  }
}

Dropdown.propTypes = {
  trigger: PropTypes.element.isRequired,
  children: PropTypes.node.isRequired,
  container: PropTypes.any,
  placement: PropTypes.oneOf(['top', 'left', 'bottom', 'right']),
  datepicker: PropTypes.bool
};

Dropdown.defaultProps = {
  placement: 'bottom',
  datepicker: false
};


@@ -1610,87 +1610,183 @@
 = %7B%0A
-  trigger: PropTypes.element.isRequired,%0A  children: PropTypes.node.isRequired,
+%0A  // The component to attach the toggle onClick to%0A  trigger: PropTypes.element.isRequired,%0A%0A  // A container to render the inner HoverCard into (will use body if not passed)
 %0A  c
@@ -1814,102 +1814,353 @@
 ny,%0A
-  placement: PropTypes.oneOf(%5B'top', 'left', 'bottom', 'right'%5D),%0A  datepicker: PropTypes.bool
+%0A  // Which side of the trigger we want the dropdown to render. The HoverCard%0A  // within will attempt alternative placements if the one designated doesnt fit%0A  placement: PropTypes.oneOf(%5B'top', 'left', 'bottom', 'right'%5D),%0A%0A  // If this dropdown contains a datepicker or not%0A  datepicker: PropTypes.bool,%0A%0A  children: PropTypes.node.isRequired
 %0A%7D;%0A

Add comments to Dropdown