import _getIterator from 'babel-runtime/core-js/get-iterator';
import _extends from 'babel-runtime/helpers/extends';
import _typeof from 'babel-runtime/helpers/typeof';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import React from 'react';
import StaticContainer from 'react-static-container';

import mergeRouteParams from './utils/mergeRouteParams';

var propTypes = {
  queries: React.PropTypes.object.isRequired,
  routerProps: React.PropTypes.object.isRequired,
  children: React.PropTypes.element.isRequired
};

var contextTypes = {
  queryAggregator: React.PropTypes.object.isRequired
};

function RouteContainer(_ref, _ref2) {
  var queries = _ref.queries;
  var routerProps = _ref.routerProps;
  var children = _ref.children;

  var extraProps = _objectWithoutProperties(_ref, ['queries', 'routerProps', 'children']);

  var queryAggregator = _ref2.queryAggregator;
  var key = routerProps.key;
  var route = routerProps.route;
  var routes = routerProps.routes;


  var params = {};
  for (var _iterator = routes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _getIterator(_iterator);;) {
    var _ref3;

    if (_isArray) {
      if (_i >= _iterator.length) break;
      _ref3 = _iterator[_i++];
    } else {
      _i = _iterator.next();
      if (_i.done) break;
      _ref3 = _i.value;
    }

    var ancestorRoute = _ref3;

    params = mergeRouteParams(params, ancestorRoute, routerProps);

    if (ancestorRoute === route) {
      break;
    }
  }

  var renderArgs = queryAggregator.getRenderArgs(route, key, queries, params);

  var props = renderArgs.props;
  var render = route.render;

  if (render && (typeof render === 'undefined' ? 'undefined' : _typeof(render)) === 'object') {
    render = render[key];
  }

  // The below is largely copied from RelayReadyStateRenderer.

  var element = void 0;
  if (render) {
    element = render.call(route, _extends({}, renderArgs, {
      props: props && _extends({}, routerProps, extraProps, params, props),
      routerProps: _extends({}, routerProps, extraProps),
      element: children
    }));
  } else if (props) {
    // The child already has routerProps, so just inject the additional props.
    element = React.cloneElement(children, _extends({}, extraProps, params, props));
  }

  var shouldUpdate = void 0;
  if (element === undefined) {
    element = null;
    shouldUpdate = false;
  } else {
    shouldUpdate = true;
  }

  return React.createElement(
    StaticContainer,
    { shouldUpdate: shouldUpdate },
    element
  );
}

RouteContainer.propTypes = propTypes;
RouteContainer.contextTypes = contextTypes;

export default RouteContainer;