import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import classnames from 'classnames';
import './index.scss';

const Root = document.querySelector('body');
const events = ['touchmove', 'mousewheel'];

class Mask extends Component {

  constructor(props) {
    super(props);
    if(!this.el) {
      this.el = document.createElement('div');
    }
  }

  componentDidMount() {
    events.forEach(item => {
      this.el.addEventListener(item, this.preventEvent, {
          passive: false
      })
    })
    Root.appendChild(this.el);
  }

  componentWillUnmount() {
    Root.removeChild(this.el);
  }

  preventEvent = e => {
    e.preventDefault();
  }

  render() {
    const { visible, handleToHide, className } = this.props;
    if(visible) {
      return ReactDOM.createPortal(
        (
          <div className="mask">
            <div className={classnames("mask-content", className)}>
              {this.props.children}
            </div>
            <div className="mask-footer">
              <i className="mask-button__close" onClick={handleToHide}></i>
            </div>
          </div>
        ),
        this.el
      );
    }else {
      return null;
    }
  }
}

export default Mask;