'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _reactTestRenderer = require('react-test-renderer');

var _reactTestRenderer2 = _interopRequireDefault(_reactTestRenderer);

var _cssLayout = require('css-layout');

var _cssLayout2 = _interopRequireDefault(_cssLayout);

var _Context = require('./utils/Context');

var _Context2 = _interopRequireDefault(_Context);

var _createStringMeasurer = require('./utils/createStringMeasurer');

var _createStringMeasurer2 = _interopRequireDefault(_createStringMeasurer);

var _debug = require('./debug');

var _hasAnyDefined = require('./utils/hasAnyDefined');

var _hasAnyDefined2 = _interopRequireDefault(_hasAnyDefined);

var _pick = require('./utils/pick');

var _pick2 = _interopRequireDefault(_pick);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var INHERITABLE_STYLES = ['color', 'fontFamily', 'fontSize', 'fontStyle', 'fontWeight', 'textShadowOffset', 'textShadowRadius', 'textShadowColor', 'textTransform', 'letterSpacing', 'lineHeight', 'textAlign', 'writingDirection'];

var reactTreeToFlexTree = function reactTreeToFlexTree(node, context) {
  if (typeof node === 'string') {
    var _textStyle = context.getInheritedStyles();
    // string node
    return {
      type: 'text',
      style: {
        measure: (0, _createStringMeasurer2.default)(node, _textStyle)
      },
      textStyle: _textStyle,
      props: {},
      value: node,
      children: []
    };
  }

  var children = node.children || [];
  var style = node.props.style || {};

  var textStyle = void 0;
  if (node.type === 'text' && node.props.style && (0, _hasAnyDefined2.default)(style, INHERITABLE_STYLES)) {
    var inheritableStyles = (0, _pick2.default)(style, INHERITABLE_STYLES);
    context.addInheritableStyles(inheritableStyles);
    textStyle = _extends({}, context.getInheritedStyles(), inheritableStyles);
  } else {
    textStyle = context.getInheritedStyles();
  }

  return {
    type: node.type,
    style: style,
    textStyle: textStyle,
    props: node.props,
    value: null,
    children: children.map(function (child) {
      return reactTreeToFlexTree(child, context.forChildren());
    })
  };
};

var buildTree = function buildTree(element) {
  var renderer = _reactTestRenderer2.default.create(element);
  var json = renderer.toJSON();
  var tree = (0, _debug.timeFunction)(function () {
    return reactTreeToFlexTree(json, new _Context2.default());
  }, '- reactTreeToFlexTree');
  (0, _debug.timeFunction)(function () {
    return (0, _cssLayout2.default)(tree);
  }, '- computeLayout');

  return tree;
};

exports.default = buildTree;