import { findParentNodeOfType } from '@atlaskit/editor-prosemirror/utils';

/**
 * Checks if the node before selection is a media node
 * If there is no node before, checks the node before the parent node
 * Includes media, mediaInline, mediaGroup, mediaSingle
 * @param $pos The position of the selection
 * @param state The editor state
 */
export var isNodeBeforeMediaNode = function isNodeBeforeMediaNode($pos, state) {
  var nodeBefore = $pos.nodeBefore;
  if (!nodeBefore) {
    var depthOfParent = $pos.depth - 1 || 1;
    var parentNode = findParentNodeOfType([state.schema.nodes["".concat($pos.node(depthOfParent).type.name)]])(state.selection);
    var resolvedPosOfParentNode = parentNode ? state.tr.doc.resolve(parentNode.pos) : undefined;
    var nodeBeforeParent = resolvedPosOfParentNode && resolvedPosOfParentNode.pos < state.doc.nodeSize ? resolvedPosOfParentNode.nodeBefore : undefined;
    if (nodeBeforeParent) {
      nodeBefore = nodeBeforeParent;
    }
  }
  if (nodeBefore) {
    return ['media', 'mediaInline', 'mediaGroup', 'mediaSingle'].includes(nodeBefore.type.name);
  }
  return false;
};