import _inheritsLoose from "@babel/runtime/helpers/inheritsLoose";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import React from 'react';
import PropTypes from 'prop-types';
export var PopupDispatcher =
/*#__PURE__*/
function (_React$Component) {
  _inheritsLoose(PopupDispatcher, _React$Component);

  // TODO (UIA-70822) for now it is hardcoded since childContextTypes is mandatory, redo with new context API when React is updated
  function PopupDispatcher() {
    var _this;

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
    _this.state = {
      stack: []
    };
    return _this;
  }

  var _proto = PopupDispatcher.prototype;

  _proto.getChildContext = function getChildContext() {
    var popupContext = this.props.popupContext;

    if (!popupContext) {
      return {};
    }

    return {
      store: popupContext.store || null
    };
  };

  _proto.showPopup = function showPopup(element) {
    var _this2 = this;

    if (element.props.onHide) {
      throw new Error('showPopup do not support onHide property of Popup');
    }

    var popup = React.cloneElement(element, {
      onHide: function onHide() {
        var stack = _this2.state.stack;
        var index = stack.indexOf(popup);

        if (index !== -1) {
          stack.splice(index, 1);

          _this2.setState({
            stack: stack
          });
        }
      }
    });
    return new Promise(function (resolve) {
      if (popup.props.stackable) {
        _this2.setState({
          stack: [].concat(_this2.state.stack, [popup])
        }, resolve);
      } else {
        _this2.setState({
          stack: [popup]
        }, resolve);
      }
    });
  };

  _proto.closePopup = function closePopup() {
    if (this.state.stack.length) {
      this.state.stack[this.state.stack.length - 1].props.onHide();
    }
  };

  _proto.render = function render() {
    return React.createElement("div", null, this.state.stack.map(function (popup, key) {
      return React.cloneElement(popup, {
        key: key
      });
    }));
  };

  return PopupDispatcher;
}(React.Component);

_defineProperty(PopupDispatcher, "propTypes", {
  popupContext: PropTypes.object
});

_defineProperty(PopupDispatcher, "defaultProps", {
  popupContext: null
});

_defineProperty(PopupDispatcher, "childContextTypes", {
  store: PropTypes.object // Redux store

});