import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _possibleConstructorReturn from "@babel/runtime/helpers/esm/possibleConstructorReturn";
import _getPrototypeOf from "@babel/runtime/helpers/esm/getPrototypeOf";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import React from 'react';
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import LoadingMessage from './LoadingMessage';
import * as selectors from '../selectors';

var LoadingSection =
/*#__PURE__*/
function (_React$Component) {
  _inherits(LoadingSection, _React$Component);

  function LoadingSection(props) {
    var _this;

    _classCallCheck(this, LoadingSection);

    _this = _possibleConstructorReturn(this, _getPrototypeOf(LoadingSection).call(this, props));

    _this.setDelay = function () {
      var delay = _this.props.delay;

      if (delay) {
        _this.delayTimer = setTimeout(function () {
          _this.setState({
            delayReached: true
          });
        }, delay);
      } else {
        _this.setState({
          delayReached: true
        });
      }
    };

    _this.clearDelay = function () {
      clearTimeout(_this.delayTimer);

      _this.setState({
        delayReached: false
      });
    };

    _this.state = {
      delayReached: false
    };
    _this.delayTimer = null;
    return _this;
  }

  _createClass(LoadingSection, [{
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps) {
      var isLoading = this.props.isLoading; // set a delay for displahying the loading indicator to avoid flashing

      if (isLoading !== prevProps.isLoading) {
        if (isLoading) {
          this.setDelay();
        } else {
          this.clearDelay();
        }
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props = this.props,
          children = _this$props.children,
          isLoading = _this$props.isLoading;
      var delayReached = this.state.delayReached;

      if (isLoading && delayReached) {
        return React.createElement(LoadingMessage, null);
      }

      return children;
    }
  }]);

  return LoadingSection;
}(React.Component);

LoadingSection.defaultProps = {
  children: null,
  delay: 200
};
export var mapStateToProps = createStructuredSelector({
  isLoading: selectors.getIsLoading()
});
var withRedux = connect(mapStateToProps);
export default withRedux(LoadingSection);