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

/**
 * This throttles the callback with requestIdleCallback.
 */
export function createThrottleSchedule(callback) {
  let frameId;
  let lastArgs;
  const delayedCallbacks = [];
  const wrapperFn = (...args) => {
    var _globalThis$requestId;
    const lastArgsBefore = lastArgs;
    lastArgs = args;
    if (frameId) {
      if (lastArgsBefore) {
        const [_v, _c, _t, _f, alwaysFire] = lastArgsBefore;
        if (alwaysFire) {
          delayedCallbacks.push(lastArgsBefore);
        }
      }
      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) {
        delayedCallbacks.forEach(savedArgs => {
          callback(...savedArgs);
        });
        callback(...lastArgs);
      }
    }, {
      timeout: 100
    });
  };
  return wrapperFn;
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function returnDocumentRequest(editorView, callback, transformer, fireAnalyticsEvent, _alwaysFire) {
  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;
  }
  try {
    const json = toJSON(doc);
    if (typeof transformer === 'undefined') {
      callback(json);
    } else {
      const nodeSanitized = PMNode.fromJSON(schema, json);
      callback(transformer.encode(nodeSanitized));
    }
  } catch (e) {
    fireAnalyticsEvent === null || fireAnalyticsEvent === void 0 ? void 0 : fireAnalyticsEvent({
      payload: {
        action: ACTION.DOCUMENT_PROCESSING_ERROR,
        actionSubject: ACTION_SUBJECT.EDITOR,
        eventType: EVENT_TYPE.OPERATIONAL,
        attributes: {
          errorMessage: `${e instanceof Error && e.name === 'NodeNestingTransformError' ? 'NodeNestingTransformError - Failed to transform one or more nested tables' : undefined}`
        }
      }
    });
    throw e;
  }
}
export function returnDocumentRequestNoThrowError(editorView, callback, transformer, fireAnalyticsEvent, _alwaysFire) {
  try {
    return returnDocumentRequest(editorView, callback, transformer, fireAnalyticsEvent, _alwaysFire);
  } catch {
    callback(undefined);
  }
}