/**
 * Created by baoyinghai on 4/24/17.
 */
import React from 'react';
/**
 * config object {querySelector, defaultShow}
 * */
export const clickSpaceWrapper = (Comp, config) => {
  class WrapperComp extends React.Component {

    constructor(props) {
      super(props);
      this.state = {
        show: !!config.defaultShow
      };
    }

    executeCb = event => {
      if (this.tag && this.tag.compareDocumentPosition(event.target) !== 20 && this.getShowState()) {
        this._switchHandler();
      }
    };

    getShowState = () => {
      if (this.props.switchHandler) {
        return !!config.defaultShow;
      }
      return this.state.show;
    };

    // add element to watch
    componentDidMount() {
      if (config.querySelector) {
        const tags = document.querySelectorAll('.' + config.querySelector);
        if (tags.length > 0) {
          this.tag = tags[tags.length - 1];
          window.addEventListener('click', this.executeCb);
        }
      } else {
        console.error('clickSpaceWrapper: ', 'no watched element!');
      }
    }

    _switchHandler = () => {
      if (this.props.switchHandler) {
        this.props.switchHandler();
      } else {
        this.setState({ show: !this.state.show });
      }
    };

    // remove listener
    componentWillUnmount() {
      window.removeEventListener('click', this.executeCb);
    }

    render() {
      return (<Comp {...this.props} refStr={config.querySelector} show={this.state.show} switchHandler={this._switchHandler} />);
    }
  }
  return WrapperComp;
};
