"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.createThrottleSchedule = createThrottleSchedule;
exports.returnDocumentRequest = returnDocumentRequest;
exports.returnDocumentRequestNoThrowError = returnDocumentRequestNoThrowError;
exports.toJSON = toJSON;
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _editorJsonTransformer = require("@atlaskit/editor-json-transformer");
var _model = require("@atlaskit/editor-prosemirror/model");
var _analytics = require("../../analytics");
var transformer = new _editorJsonTransformer.JSONTransformer();
function toJSON(node) {
  return transformer.encode(node);
}

/**
 * This throttles the callback with requestIdleCallback.
 */
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 = (0, _slicedToArray2.default)(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, (0, _toConsumableArray2.default)(savedArgs));
        });
        callback.apply(void 0, (0, _toConsumableArray2.default)(lastArgs));
      }
    }, {
      timeout: 100
    });
  };
  return wrapperFn;
}

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