"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = convertFromJSON;

var _prosemirrorModel = require("prosemirror-model");

var _prosemirrorState = require("prosemirror-state");

var _createEmptyEditorState = _interopRequireDefault(require("./createEmptyEditorState"));

var _EditorToolbarConfig = require("./ui/EditorToolbarConfig");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function convertFromJSON(json, schema, defaultSchema, plugins, defaultPlugins) {
  let editorSchema = schema || defaultSchema; // [FS][IRAD-???? 2020-08-17]
  // Loads plugins and its corresponding schema in editor

  const effectivePlugins = defaultPlugins;

  if (plugins) {
    for (const p of plugins) {
      if (!effectivePlugins.includes(p)) {
        effectivePlugins.push(p);

        if (p.getEffectiveSchema) {
          editorSchema = p.getEffectiveSchema(editorSchema);
        }

        if (p.initKeyCommands) {
          effectivePlugins.push(p.initKeyCommands());
        }

        if (p.initButtonCommands) {
          _EditorToolbarConfig.COMMAND_GROUPS.push(p.initButtonCommands());
        }
      }
    }
  }

  if (typeof json === 'string') {
    try {
      json = JSON.parse(json);
    } catch (ex) {
      console.error('convertFromJSON:', ex); // [FS] IRAD-1455 2021-06-16
      // Use the effectivePlugins, editor hangs, b'coz of missing default core plugins

      return (0, _createEmptyEditorState.default)(schema, defaultSchema, plugins, defaultPlugins);
    }
  }

  if (!json || typeof json !== 'object') {
    console.error('convertFromJSON: invalid object', json); // [FS] IRAD-1455 2021-06-16
    // Use the effectivePlugins, editor hangs, b'coz of missing default core plugins

    return (0, _createEmptyEditorState.default)(schema, defaultSchema, plugins, defaultPlugins);
  } // [FS] IRAD-1067 2020-09-19
  // Handle gracefully when error thrown on invalid json


  let doc = null;

  try {
    doc = editorSchema.nodeFromJSON(json);
  } catch (error) {
    return null;
  }

  return _prosemirrorState.EditorState.create({
    doc: doc,
    schema: editorSchema,
    plugins: effectivePlugins
  });
}