import _defineProperty from "@babel/runtime/helpers/defineProperty";
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
import React from 'react';
import { TextSelection } from '@atlaskit/editor-prosemirror/state';
import { fg } from '@atlaskit/platform-feature-flags';
import { ACTION } from '../../analytics';
import { sendMBEAnalyticsEvent } from './utils';
export var useMultiBodiedExtensionActions = function useMultiBodiedExtensionActions(_ref) {
  var updateActiveChild = _ref.updateActiveChild,
    editorView = _ref.editorView,
    getPos = _ref.getPos,
    node = _ref.node,
    eventDispatcher = _ref.eventDispatcher,
    allowBodiedOverride = _ref.allowBodiedOverride,
    childrenContainer = _ref.childrenContainer;
  var actions = React.useMemo(function () {
    return {
      changeActive: function changeActive(index) {
        var _possiblyMbeNode$type;
        var state = editorView.state,
          dispatch = editorView.dispatch;
        var updateActiveChildResult = updateActiveChild(index);
        if (eventDispatcher) {
          sendMBEAnalyticsEvent(ACTION.CHANGE_ACTIVE, node, eventDispatcher);
        }
        // On selection of a childFrame, we need to change the focus/selection to the end of the target child Frame
        var pos = getPos();
        if (typeof pos !== 'number') {
          return updateActiveChildResult;
        }
        var possiblyMbeNode = state.doc.nodeAt(pos);
        var desiredPos = pos;
        if (possiblyMbeNode && (possiblyMbeNode === null || possiblyMbeNode === void 0 || (_possiblyMbeNode$type = possiblyMbeNode.type) === null || _possiblyMbeNode$type === void 0 ? void 0 : _possiblyMbeNode$type.name) === 'multiBodiedExtension' && possiblyMbeNode !== null && possiblyMbeNode !== void 0 && possiblyMbeNode.content) {
          var _possiblyMbeNode$cont;
          if (index < 0 || index >= (possiblyMbeNode === null || possiblyMbeNode === void 0 || (_possiblyMbeNode$cont = possiblyMbeNode.content) === null || _possiblyMbeNode$cont === void 0 ? void 0 : _possiblyMbeNode$cont.childCount)) {
            var _possiblyMbeNode$cont2;
            throw new Error("Index out of bounds: valid range is 0-".concat((possiblyMbeNode === null || possiblyMbeNode === void 0 || (_possiblyMbeNode$cont2 = possiblyMbeNode.content) === null || _possiblyMbeNode$cont2 === void 0 ? void 0 : _possiblyMbeNode$cont2.childCount) - 1, " inclusive"));
          }
          for (var i = 0; i <= index && i < (possiblyMbeNode === null || possiblyMbeNode === void 0 || (_possiblyMbeNode$cont3 = possiblyMbeNode.content) === null || _possiblyMbeNode$cont3 === void 0 ? void 0 : _possiblyMbeNode$cont3.childCount); i++) {
            var _possiblyMbeNode$cont3, _possiblyMbeNode$cont4;
            desiredPos += (possiblyMbeNode === null || possiblyMbeNode === void 0 || (_possiblyMbeNode$cont4 = possiblyMbeNode.content) === null || _possiblyMbeNode$cont4 === void 0 || (_possiblyMbeNode$cont4 = _possiblyMbeNode$cont4.child(i)) === null || _possiblyMbeNode$cont4 === void 0 ? void 0 : _possiblyMbeNode$cont4.nodeSize) || 0;
          }
          /* desiredPos gives the cursor at the end of last child of the current frame, in case of paragraph nodes, this will be the end of the paragraph
           * Performing -1 brings the cursor inside the paragraph, similar to a user click, so any pasted text will be inside the last paragraph rather than a new line
           */
          dispatch(state.tr.setSelection(new TextSelection(state.doc.resolve(desiredPos - 1))));
        }
        return updateActiveChildResult;
      },
      addChild: function addChild() {
        var state = editorView.state,
          dispatch = editorView.dispatch;
        var p = state.schema.nodes.paragraph.createAndFill({});
        if (!p) {
          throw new Error('Could not create paragraph');
        }
        var frame = state.schema.nodes.extensionFrame.createAndFill({}, [p]);
        var pos = getPos();
        if (typeof pos !== 'number' || !frame) {
          throw new Error('Could not create frame or position not valid');
        }
        var insertAt = Math.min((pos || 1) + node.content.size, state.doc.content.size);
        var tr = state.tr.insert(insertAt, frame);
        tr.setSelection(new TextSelection(tr.doc.resolve(insertAt + 1)));
        dispatch(tr);
        if (eventDispatcher) {
          sendMBEAnalyticsEvent(ACTION.ADD_CHILD, node, eventDispatcher);
        }
        return true;
      },
      getChildrenCount: function getChildrenCount() {
        return node.content.childCount;
      },
      removeChild: function removeChild(index) {
        var pos = getPos();
        // Ignored via go/ees007
        // eslint-disable-next-line @atlaskit/editor/enforce-todo-comment-format
        // TODO: Add child index validation here, don't trust this data
        if (typeof pos !== 'number' || typeof index !== 'number') {
          throw new Error('Position or index not valid');
        }
        var state = editorView.state,
          dispatch = editorView.dispatch;
        if (node.content.childCount === 1) {
          var _tr = state.tr;
          _tr.deleteRange(pos, pos + node.content.size);
          dispatch(_tr);
          return true;
        }
        var $pos = state.doc.resolve(pos);
        var $startNodePos = state.doc.resolve($pos.start($pos.depth + 1));
        var startFramePosition = $startNodePos.posAtIndex(index);
        var maybeFrameNode = state.doc.nodeAt(startFramePosition);
        if (!maybeFrameNode) {
          throw new Error('Could not find frame node');
        }
        var endFramePosition = maybeFrameNode.content.size + startFramePosition;
        var tr = state.tr;
        tr.deleteRange(startFramePosition, endFramePosition);
        dispatch(tr);
        if (eventDispatcher) {
          sendMBEAnalyticsEvent(ACTION.REMOVE_CHILD, node, eventDispatcher);
        }
        return true;
      },
      updateParameters: function updateParameters(parameters) {
        var state = editorView.state,
          dispatch = editorView.dispatch;
        var pos = getPos();
        if (typeof pos !== 'number') {
          throw new Error('Position not valid');
        }
        // We are retaining node.attrs to keep the node type and extension key
        // and only updating the parameters coming in from the user
        // parameters will contain only macroParams information
        var updatedParameters = _objectSpread(_objectSpread({}, node.attrs), {}, {
          parameters: _objectSpread(_objectSpread({}, node.attrs.parameters), fg('confluence_frontend_native_tabs_extension') ? _objectSpread({}, parameters) : {
            macroParams: parameters
          })
        });
        var tr = state.tr.setNodeMarkup(pos, null, updatedParameters);
        dispatch(tr);
        if (eventDispatcher) {
          sendMBEAnalyticsEvent(ACTION.UPDATE_PARAMETERS, node, eventDispatcher);
        }
        return true;
      },
      getChildren: function getChildren() {
        var _state$doc$nodeAt;
        var state = editorView.state;
        var pos = getPos();
        if (typeof pos !== 'number') {
          return [];
        }
        var children = (_state$doc$nodeAt = state.doc.nodeAt(pos)) === null || _state$doc$nodeAt === void 0 ? void 0 : _state$doc$nodeAt.content;
        if (eventDispatcher) {
          sendMBEAnalyticsEvent(ACTION.GET_CHILDREN, node, eventDispatcher);
        }
        return children ? children.toJSON() : [];
      },
      getChildrenContainer: function getChildrenContainer() {
        if (!allowBodiedOverride) {
          throw new Error('Could not provide children container');
        }
        if (eventDispatcher) {
          sendMBEAnalyticsEvent(ACTION.GET_CHILDREN_CONTAINER, node, eventDispatcher);
        }
        return childrenContainer;
      }
    };
  }, [node, editorView, getPos, updateActiveChild, eventDispatcher, allowBodiedOverride, childrenContainer]);
  return actions;
};