import React, { Component } from 'react'
import ReactDOM from 'react-dom'

function isInsideElement (e1, e2) {
  if (e1 === null) {
    return false
  }
  return e1 === e2 || isInsideElement(e1.parentNode, e2)
}

export default (WrappedComponent) => class MTOutsideClickCloseHoc extends Component {
  constructor (props) {
    super(props)
    this.state = {
      isHidden: true,
      shouldHandleOutsideClick: undefined,
    }
    this.toggle = this.toggle.bind(this)
    this.open = this.open.bind(this)
    this.close = this.close.bind(this)
    this._outsideClickListener = this._outsideClickListener.bind(this)
    this.listenForOutsideClick = this.listenForOutsideClick.bind(this)
    this.stopListenForOutsideClick = this.stopListenForOutsideClick.bind(this)
    this.setShouldHandleOutsideClickFn = this.setShouldHandleOutsideClickFn.bind(this)
  }

  componentWillUnmount () {
    this.stopListenForOutsideClick()
  }

  setShouldHandleOutsideClickFn (fn) {
    this.setState({ shouldHandleOutsideClick: fn })
  }

  open () {
    this.setState({ isHidden: false })
    this.listenForOutsideClick()
  }

  close () {
    this.setState({ isHidden: true })
    this.stopListenForOutsideClick()
  }

  toggle () {
    if (this.state.isHidden) {
      this.open()
    } else {
      this.close()
    }
  }

  _outsideClickListener (e) {
    const { shouldHandleOutsideClick } = this.state
    // eslint-disable-next-line react/no-find-dom-node
    if (!isInsideElement(e.target, ReactDOM.findDOMNode(this))) {
      if (shouldHandleOutsideClick === undefined || shouldHandleOutsideClick(e)) {
        this.close()
      }
    }
  }

  listenForOutsideClick () {
    document.addEventListener('mousedown', this._outsideClickListener)
  }

  stopListenForOutsideClick () {
    document.removeEventListener('mousedown', this._outsideClickListener)
  }

  render () {
    const { isHidden } = this.state
    return (
      <WrappedComponent
        isHidden={ isHidden }
        toggle={ this.toggle }
        setShouldHandleOutsideClickFn={ this.setShouldHandleOutsideClickFn }
        { ...this.props }
        open={ this.open }
        close={ this.close }
      />
    )
  }
}
