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, { Children, cloneElement } from 'react';
import get from 'lodash/get';
export var Guard =
/*#__PURE__*/
function (_React$Component) {
  _inherits(Guard, _React$Component);

  function Guard() {
    _classCallCheck(this, Guard);

    return _possibleConstructorReturn(this, _getPrototypeOf(Guard).apply(this, arguments));
  }

  _createClass(Guard, [{
    key: "render",
    value: function render() {
      var _this$props = this.props,
          Component = _this$props.Component,
          children = _this$props.children,
          props = _this$props.props,
          when = _this$props.when,
          otherwise = _this$props.otherwise;
      var hasWhen;
      return Children.map(children, function (child) {
        if (!React.isValidElement(child)) {
          return null;
        }

        if (when && get(child.props, when) || typeof when === 'undefined') {
          // hasWhen define whether we want to render otherwise or not
          hasWhen = get(child.props, when);

          if (Component && Component.isPrototypeOf(child.type) || child.type === Component) {
            return cloneElement(child, props);
          }
        }

        if (!hasWhen && otherwise) {
          if (!(Component && Component.isPrototypeOf(child.type) || child.type === Component)) {
            return otherwise();
          }
        }

        return null;
      });
    }
  }]);

  return Guard;
}(React.Component);