import React from 'react';
import { TextSelection } from '@atlaskit/editor-prosemirror/state';
import { getBooleanFF } from '@atlaskit/platform-feature-flags';
import { ACTION } from '../../analytics';
import { sendMBEAnalyticsEvent } from './utils';
export const useMultiBodiedExtensionActions = ({
  updateActiveChild,
  editorView,
  getPos,
  node,
  eventDispatcher
}) => {
  const actions = React.useMemo(() => {
    return {
      changeActive(index) {
        var _possiblyMbeNode$type;
        const {
          state,
          dispatch
        } = editorView;
        const 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
        const pos = getPos();
        if (typeof pos !== 'number') {
          return updateActiveChildResult;
        }
        const possiblyMbeNode = state.doc.nodeAt(pos);
        let desiredPos = pos;
        if (possiblyMbeNode && (possiblyMbeNode === null || possiblyMbeNode === void 0 ? 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 ? 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-${(possiblyMbeNode === null || possiblyMbeNode === void 0 ? void 0 : (_possiblyMbeNode$cont2 = possiblyMbeNode.content) === null || _possiblyMbeNode$cont2 === void 0 ? void 0 : _possiblyMbeNode$cont2.childCount) - 1} inclusive`);
          }
          for (let i = 0; i <= index && i < (possiblyMbeNode === null || possiblyMbeNode === void 0 ? void 0 : (_possiblyMbeNode$cont3 = possiblyMbeNode.content) === null || _possiblyMbeNode$cont3 === void 0 ? void 0 : _possiblyMbeNode$cont3.childCount); i++) {
            var _possiblyMbeNode$cont3, _possiblyMbeNode$cont4, _possiblyMbeNode$cont5;
            desiredPos += (possiblyMbeNode === null || possiblyMbeNode === void 0 ? void 0 : (_possiblyMbeNode$cont4 = possiblyMbeNode.content) === null || _possiblyMbeNode$cont4 === void 0 ? void 0 : (_possiblyMbeNode$cont5 = _possiblyMbeNode$cont4.child(i)) === null || _possiblyMbeNode$cont5 === void 0 ? void 0 : _possiblyMbeNode$cont5.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() {
        const {
          state,
          dispatch
        } = editorView;
        const p = state.schema.nodes.paragraph.createAndFill({});
        if (!p) {
          throw new Error('Could not create paragraph');
        }
        const frame = state.schema.nodes.extensionFrame.createAndFill({}, [p]);
        const pos = getPos();
        if (typeof pos !== 'number' || !frame) {
          throw new Error('Could not create frame or position not valid');
        }
        const insertAt = Math.min((pos || 1) + node.content.size, state.doc.content.size);
        const 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() {
        return node.content.childCount;
      },
      removeChild(index) {
        const 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');
        }
        const {
          state,
          dispatch
        } = editorView;
        if (node.content.childCount === 1) {
          const tr = state.tr;
          tr.deleteRange(pos, pos + node.content.size);
          dispatch(tr);
          return true;
        }
        const $pos = state.doc.resolve(pos);
        const $startNodePos = state.doc.resolve($pos.start($pos.depth + 1));
        const startFramePosition = $startNodePos.posAtIndex(index);
        const maybeFrameNode = state.doc.nodeAt(startFramePosition);
        if (!maybeFrameNode) {
          throw new Error('Could not find frame node');
        }
        const endFramePosition = maybeFrameNode.content.size + startFramePosition;
        const tr = state.tr;
        tr.deleteRange(startFramePosition, endFramePosition);
        dispatch(tr);
        if (eventDispatcher) {
          sendMBEAnalyticsEvent(ACTION.REMOVE_CHILD, node, eventDispatcher);
        }
        return true;
      },
      updateParameters(parameters) {
        const {
          state,
          dispatch
        } = editorView;
        const 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
        let updatedParameters;
        if (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 = {
            ...node.attrs,
            parameters: {
              ...node.attrs.parameters,
              macroParams: parameters
            }
          };
        } else {
          var _node$attrs, _node$attrs$parameter;
          updatedParameters = {
            ...node.attrs,
            parameters: {
              ...node.attrs.parameters,
              macroParams: {
                ...((_node$attrs = node.attrs) === null || _node$attrs === void 0 ? void 0 : (_node$attrs$parameter = _node$attrs.parameters) === null || _node$attrs$parameter === void 0 ? void 0 : _node$attrs$parameter.macroParams),
                ...parameters
              }
            }
          };
        }
        const tr = state.tr.setNodeMarkup(pos, null, updatedParameters);
        dispatch(tr);
        if (eventDispatcher) {
          sendMBEAnalyticsEvent(ACTION.UPDATE_PARAMETERS, node, eventDispatcher);
        }
        return true;
      },
      getChildren() {
        var _state$doc$nodeAt;
        const {
          state
        } = editorView;
        const pos = getPos();
        if (typeof pos !== 'number') {
          return [];
        }
        const 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_CHILDERN, node, eventDispatcher);
        }
        return children ? children.toJSON() : [];
      }
    };
  }, [node, editorView, getPos, updateActiveChild, eventDispatcher]);
  return actions;
};