import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import { JSONTransformer } from '@atlaskit/editor-json-transformer';
import { Node as PMNode } from '@atlaskit/editor-prosemirror/model';
import { ACTION, ACTION_SUBJECT, EVENT_TYPE } from '../../analytics';
var transformer = new JSONTransformer();
export function toJSON(node) {
  return transformer.encode(node);
}

/**
 * This throttles the callback with requestIdleCallback.
 */
export function createThrottleSchedule(callback) {
  var frameId;
  var lastArgs;
  var delayedCallbacks = [];
  var wrapperFn = function wrapperFn() {
    var _globalThis$requestId;
    var lastArgsBefore = lastArgs;
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    lastArgs = args;
    if (frameId) {
      if (lastArgsBefore) {
        var _lastArgsBefore = _slicedToArray(lastArgsBefore, 5),
          _v = _lastArgsBefore[0],
          _c = _lastArgsBefore[1],
          _t = _lastArgsBefore[2],
          _f = _lastArgsBefore[3],
          alwaysFire = _lastArgsBefore[4];
        if (alwaysFire) {
          delayedCallbacks.push(lastArgsBefore);
        }
      }
      return;
    }

    // If `requestIdleCallback` doesn't exist - fallback to `requestAnimationFrame`
    var delayFunction = (_globalThis$requestId = globalThis.requestIdleCallback) !== null && _globalThis$requestId !== void 0 ? _globalThis$requestId : globalThis.requestAnimationFrame;
    frameId = delayFunction(function () {
      frameId = undefined;
      if (lastArgs) {
        delayedCallbacks.forEach(function (savedArgs) {
          callback.apply(void 0, _toConsumableArray(savedArgs));
        });
        callback.apply(void 0, _toConsumableArray(lastArgs));
      }
    }, {
      timeout: 100
    });
  };
  return wrapperFn;
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function returnDocumentRequest(editorView, callback, transformer, fireAnalyticsEvent,
// eslint-disable-next-line no-unused-vars
_alwaysFire) {
  var _editorView$state;
  var _ref = (_editorView$state = editorView === null || editorView === void 0 ? void 0 : editorView.state) !== null && _editorView$state !== void 0 ? _editorView$state : {},
    doc = _ref.doc,
    schema = _ref.schema;
  if (!doc || !schema) {
    return undefined;
  }
  try {
    var json = toJSON(doc);
    if (typeof transformer === 'undefined') {
      callback(json);
    } else {
      var nodeSanitized = PMNode.fromJSON(schema, json);
      callback(transformer.encode(nodeSanitized));
    }
  } catch (e) {
    fireAnalyticsEvent === null || fireAnalyticsEvent === void 0 || fireAnalyticsEvent({
      payload: {
        action: ACTION.DOCUMENT_PROCESSING_ERROR,
        actionSubject: ACTION_SUBJECT.EDITOR,
        eventType: EVENT_TYPE.OPERATIONAL,
        attributes: {
          errorMessage: "".concat(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);
    // eslint-disable-next-line no-unused-vars
  } catch (_) {
    callback(undefined);
  }
}