"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

exports.__esModule = true;
exports.PopupDispatcher = void 0;

var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _react = _interopRequireDefault(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var PopupDispatcher =
/*#__PURE__*/
function (_React$Component) {
  (0, _inheritsLoose2.default)(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.default.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.default.createElement("div", null, this.state.stack.map(function (popup, key) {
      return _react.default.cloneElement(popup, {
        key: key
      });
    }));
  };

  return PopupDispatcher;
}(_react.default.Component);

exports.PopupDispatcher = PopupDispatcher;
(0, _defineProperty2.default)(PopupDispatcher, "propTypes", {
  popupContext: _propTypes.default.object
});
(0, _defineProperty2.default)(PopupDispatcher, "defaultProps", {
  popupContext: null
});
(0, _defineProperty2.default)(PopupDispatcher, "childContextTypes", {
  store: _propTypes.default.object // Redux store

});