import { EditorView } from 'prosemirror-view';
import convertToJSON from './convertToJSON.js';
import CustomEditorView from './ui/CustomEditorView.js';
import { UICommand } from '@modusoperandi/licit-doc-attrs-step';
var commandsRegistery = new Map();
var viewsRegistery = new Map();

// This file exports methods to help developer to debug editor from web
// inspector. To use this, add the following lines to export the utility.
//
//   import * as CZIProseMirror from 'czi-prosemirror/dist/CZIProseMirror';
//   window.CZIProseMirror = CZIProseMirror;

export function registeryKeys() {
  return Array.from(viewsRegistery.keys());
}
export function exportJSON(id) {
  if (!id && viewsRegistery.size) {
    id = registeryKeys()[0];
    console.log("use default editor id \"".concat(id, "\""));
  }
  var view = viewsRegistery.get(String(id));
  if (!view) {
    if (!id) {
      id = '';
    }
    throw new Error("view ".concat(id, " does not exist"));
  }
  return convertToJSON(view.state);
}
export function registerEditorView(id, view) {
  if (viewsRegistery.has(id)) {
    throw new Error("view ".concat(id, " already registered"));
  }
  if (!(view instanceof CustomEditorView)) {
    throw new Error("invalid view ".concat(id));
  }
  if (!id) {
    throw new Error('id is required');
  }
  viewsRegistery.set(id, view);
}
export function releaseEditorView(id) {
  if (!viewsRegistery.has(id)) {
    throw new Error("view ".concat(id, " was released"));
  }
  viewsRegistery["delete"](id);
}
export function findEditorView(id) {
  return viewsRegistery.get(id) || null;
}
export function executeCommand(name, viewID) {
  var command = commandsRegistery.get(name);
  if (command) {
    var view = viewID ? viewsRegistery.get(viewID) : Array.from(viewsRegistery.values())[0];
    if (view) {
      try {
        return command.execute(view.state, view.dispatch, view, null);
      } catch (ex) {
        console.warn(ex);
        return false;
      }
    }
  }
  return false;
}
export function registerCommand(name, command) {
  if (!(command instanceof UICommand)) {
    throw new Error("invalid command ".concat(name));
  }
  if (!name) {
    throw new Error('invalid command name');
  }
  if (commandsRegistery.has(name)) {
    throw new Error("command ".concat(name, " already registered"));
  }
  commandsRegistery.set(name, command);
}