'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.render = exports.renderToJSON = undefined;

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _sketchappJsonPlugin = require('sketchapp-json-plugin');

var _buildTree = require('./buildTree');

var _buildTree2 = _interopRequireDefault(_buildTree);

var _flexToSketchJSON = require('./flexToSketchJSON');

var _flexToSketchJSON2 = _interopRequireDefault(_flexToSketchJSON);

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

var _RedBox = require('./components/RedBox');

var _RedBox2 = _interopRequireDefault(_RedBox);

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

var renderToJSON = exports.renderToJSON = function renderToJSON(element) {
  var tree = (0, _debug.timeFunction)(function () {
    return (0, _buildTree2.default)(element);
  }, 'build tree');
  return (0, _flexToSketchJSON2.default)(tree);
};

var renderToSketch = function renderToSketch(node, container) {
  var json = (0, _flexToSketchJSON2.default)(node);
  var layer = (0, _sketchappJsonPlugin.fromSJSONDictionary)(json);
  container.replaceAllLayersWithLayers([layer]);
  return container;
};

var render = exports.render = function render(element, container) {
  if ((0, _sketchappJsonPlugin.appVersionSupported)()) {
    try {
      var tree = (0, _debug.timeFunction)(function () {
        return (0, _buildTree2.default)(element);
      }, 'build tree');
      return (0, _debug.timeFunction)(function () {
        return renderToSketch(tree, container);
      }, 'new renderer');
    } catch (err) {
      var _tree = (0, _buildTree2.default)(_react2.default.createElement(_RedBox2.default, { error: err }));
      return (0, _debug.timeFunction)(function () {
        return renderToSketch(_tree, container);
      }, 'new renderer');
    }
  }
  return null;
};