import PropTypes from 'prop-types';
import React from 'react';
import Modal from 'react-responsive-modal';
import logo from '../../images/loader.gif';

/**
 * React component used to render a box overlayed on top of the page
 */
class OverlayBox extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isChildComponentVisible: false,
    };

    this.onEntered = this.onEntered.bind(this);
    this.onExited = this.onExited.bind(this);
  }

  render() {
    return (
      <Modal
        animationDuration={0}
        classNames={this.props.classNames}
        onClose={this.props.onClose ? this.props.onClose : () => null}
        onEntered={this.onEntered}
        onExited={this.onExited}
        open={this.props.open}
        blockScroll={false}
        showCloseIcon={this.props.onClose ? true : false}
        focusTrapped={false}
        center
      >
        {this.state.isChildComponentVisible ? (
          this.props.children
        ) : (
          <img
            src={logo}
            alt="logo"
            style={{
              position: 'absolute',
              left: '50%',
              marginLeft: '-25px',
              top: '50%',
              marginTop: '-25px',
              height: 50,
              width: 50,
            }}
          />
        )}
      </Modal>
    );
  }

  /** Callback triggered when the overlay box is opened. */
  onEntered() {
    /** this is a trick to circumvent a bug with tinymce in modals. the modal needs to be displayed first and tinymce shown afterwards otherwise a bug occurs in tinymce. */
    setTimeout(() => {
      this.setState({ isChildComponentVisible: true });
    }, 100);
  }

  /**
   * Callback triggered when the modal is close. This happends when props.open becomes false
   */
  onExited() {
    this.setState({ isChildComponentVisible: false });
  }
}

OverlayBox.propTypes = {
  /** css classes used by the overlay box */
  classNames: PropTypes.object,
  /** when set to true the OverlayBox is opened. */
  open: PropTypes.bool,
};

export default OverlayBox;
