import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
import React from "react";
import { useHandler } from "../../../../hooks/useHandler";
import { connect } from "../../../redux";
import { getPlugins } from "../../../../plugins";
import { set } from "dot-prop-immutable";
import { getActiveElementWithChildren } from "../../../selectors";
import { cloneElement } from "../../../utils";
import { getElementWithChildren, getParentElementWithChildren } from "../../../selectors";

var CloneAction = function CloneAction(props) {
  var element = props.element,
      children = props.children;
  var onClick = useHandler(props, function (_ref) {
    var element = _ref.element,
        state = _ref.state,
        updateElement = _ref.updateElement;
    return function () {
      element = getElementWithChildren(state, element.id);
      var parent = getParentElementWithChildren(state, element.id);
      var position = parent.elements.findIndex(function (el) {
        return el.id === element.id;
      }) + 1;
      var newElement = set(parent, "elements", [].concat(_toConsumableArray(parent.elements.slice(0, position)), [cloneElement(element)], _toConsumableArray(position < parent.elements.length ? parent.elements.slice(position) : [])));
      updateElement({
        element: newElement
      });
    };
  });
  var plugin = getPlugins("pb-editor-page-element").find(function (pl) {
    return pl.elementType === element.type;
  });

  if (!plugin) {
    return null;
  }

  return /*#__PURE__*/React.cloneElement(children, {
    onClick: onClick
  });
};

var mapDispatchToProps = function mapDispatchToProps(dispatch) {
  return {
    updateElement: function updateElement(payload) {
      dispatch({
        type: 'appBuilder/updateAndFlattenElement',
        payload: payload
      });
    }
  };
};

export default connect(function (state, props) {
  var param = {};

  if (!props.element) {
    param.element = getActiveElementWithChildren(state);
  }

  param.state = state;
  return param;
}, mapDispatchToProps)(CloneAction);
//# sourceMappingURL=CloneAction.js.map