import { JSONTransformer } from '@atlaskit/editor-json-transformer';
import { Node as PMNode } from '@atlaskit/editor-prosemirror/model';
const transformer = new JSONTransformer();
export function toJSON(node) {
  return transformer.encode(node);
}

/**
 * This throttles the callback with requestIdleCallback.
 */
function createThrottleSchedule(callback) {
  let frameId;
  let lastArgs;
  const wrapperFn = (...args) => {
    var _globalThis$requestId;
    lastArgs = args;
    if (frameId) {
      return;
    }

    // If `requestIdleCallback` doesn't exist - fallback to `requestAnimationFrame`
    const delayFunction = (_globalThis$requestId = globalThis.requestIdleCallback) !== null && _globalThis$requestId !== void 0 ? _globalThis$requestId : globalThis.requestAnimationFrame;
    frameId = delayFunction(() => {
      frameId = undefined;
      if (lastArgs) {
        callback(...lastArgs);
      }
    }, {
      timeout: 100
    });
  };
  return wrapperFn;
}
export const scheduleDocumentRequest = createThrottleSchedule(returnDocumentRequest);
function returnDocumentRequest(editorView, callback, transformer) {
  var _editorView$state;
  const {
    doc,
    schema
  } = (_editorView$state = editorView === null || editorView === void 0 ? void 0 : editorView.state) !== null && _editorView$state !== void 0 ? _editorView$state : {};
  if (!doc || !schema) {
    return undefined;
  }
  const json = toJSON(doc);
  if (typeof transformer === 'undefined') {
    callback(json);
  } else {
    const nodeSanitized = PMNode.fromJSON(schema, json);
    callback(transformer.encode(nodeSanitized));
  }
}