"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useMultiBodiedExtensionActions = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _react = _interopRequireDefault(require("react"));
var _state = require("@atlaskit/editor-prosemirror/state");
var _platformFeatureFlags = require("@atlaskit/platform-feature-flags");
var _analytics = require("../../analytics");
var _utils = require("./utils");
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) { (0, _defineProperty2.default)(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; }
var useMultiBodiedExtensionActions = exports.useMultiBodiedExtensionActions = function useMultiBodiedExtensionActions(_ref) {
  var updateActiveChild = _ref.updateActiveChild,
    editorView = _ref.editorView,
    getPos = _ref.getPos,
    node = _ref.node,
    eventDispatcher = _ref.eventDispatcher;
  var actions = _react.default.useMemo(function () {
    return {
      changeActive: function changeActive(index) {
        var _possiblyMbeNode$type;
        var state = editorView.state,
          dispatch = editorView.dispatch;
        var updateActiveChildResult = updateActiveChild(index);
        if (eventDispatcher) {
          (0, _utils.sendMBEAnalyticsEvent)(_analytics.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 _state.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 _state.TextSelection(tr.doc.resolve(insertAt + 1)));
        dispatch(tr);
        if (eventDispatcher) {
          (0, _utils.sendMBEAnalyticsEvent)(_analytics.ACTION.ADD_CHILD, node, eventDispatcher);
        }
        return true;
      },
      getChildrenCount: function getChildrenCount() {
        return node.content.childCount;
      },
      removeChild: function removeChild(index) {
        var pos = getPos();
        // 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) {
          (0, _utils.sendMBEAnalyticsEvent)(_analytics.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;
        if ((0, _platformFeatureFlags.getBooleanFF)('platform.editor.mbe-update-params-change')) {
          // With the new feature flag, we will not be de-structuring macroParams,
          // and will directly replace/overwrite the macroParams with the parameters
          updatedParameters = _objectSpread(_objectSpread({}, node.attrs), {}, {
            parameters: _objectSpread(_objectSpread({}, node.attrs.parameters), {}, {
              macroParams: parameters
            })
          });
        } else {
          var _node$attrs;
          updatedParameters = _objectSpread(_objectSpread({}, node.attrs), {}, {
            parameters: _objectSpread(_objectSpread({}, node.attrs.parameters), {}, {
              macroParams: _objectSpread(_objectSpread({}, (_node$attrs = node.attrs) === null || _node$attrs === void 0 || (_node$attrs = _node$attrs.parameters) === null || _node$attrs === void 0 ? void 0 : _node$attrs.macroParams), parameters)
            })
          });
        }
        var tr = state.tr.setNodeMarkup(pos, null, updatedParameters);
        dispatch(tr);
        if (eventDispatcher) {
          (0, _utils.sendMBEAnalyticsEvent)(_analytics.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) {
          (0, _utils.sendMBEAnalyticsEvent)(_analytics.ACTION.GET_CHILDERN, node, eventDispatcher);
        }
        return children ? children.toJSON() : [];
      }
    };
  }, [node, editorView, getPos, updateActiveChild, eventDispatcher]);
  return actions;
};