import * as m from "monaco-editor";
import { toValue as a, watch as g } from "vue";
const L = "json-focus-highlight", S = ({
  element: f,
  onChange: h,
  actions: p,
  readOnly: l = !1,
  model: s
}) => {
  const n = () => a(s), t = m.editor.create(f, {
    model: n().model,
    automaticLayout: !0,
    folding: !0,
    showFoldingControls: "always",
    glyphMargin: !0,
    lineNumbers: "on",
    minimap: { enabled: !1 },
    overviewRulerLanes: 0,
    readOnly: a(l),
    scrollbar: {
      useShadows: !1,
      verticalScrollbarSize: 5
    },
    scrollBeyondLastLine: !1,
    guides: {
      indentation: !0
    },
    formatOnPaste: !0,
    renderValidationDecorations: "on",
    formatOnType: !0,
    lineHeight: 20,
    renderLineHighlight: "none",
    fontFamily: "'JetBrains Mono', monospace"
  });
  t.updateOptions({ insertSpaces: !0, tabSize: 2 }), g(s, (e) => {
    t.setModel(a(e).model);
  });
  let u = [], i = 0;
  p?.forEach((e) => {
    t.addAction({
      id: e.id,
      label: e.label,
      keybindings: e.keybindings,
      run: async () => {
        await e.run();
      }
    });
  });
  const r = async (e) => {
    await t.getAction(e)?.run();
  }, c = async (e) => {
    const o = await Promise.resolve(n().getRangeFromPath(e));
    o && (u = t.deltaDecorations(u, [
      {
        range: o,
        options: {
          className: L
        }
      }
    ]));
  }, y = async (e) => {
    const o = await Promise.resolve(n().getRangeFromPath(e));
    if (!o)
      return;
    const w = n().model, b = new m.Range(
      o.startLineNumber,
      1,
      o.endLineNumber,
      w.getLineMaxColumn(o.endLineNumber)
    );
    await r("editor.foldAll"), t.setSelection(b), await r("editor.unfoldRecursively");
    const d = { lineNumber: o.startLineNumber, column: o.startColumn };
    t.setPosition(d), t.revealPositionNearTop(d), await c(e);
  };
  return t.onDidChangeModelContent(() => {
    if (i > 0) {
      i -= 1;
      return;
    }
    const e = t.getValue();
    typeof e == "string" && h?.(e ?? "");
  }), g(
    () => a(l),
    (e) => {
      t?.updateOptions({ readOnly: e });
    }
  ), {
    editor: t,
    model: s,
    highlightPath: c,
    focusPath: y,
    formatDocument: async () => {
      await r("editor.action.formatDocument");
    },
    getValue: () => t.getValue(),
    setValue: (e, o = !1) => {
      o && (i += 1), t.setValue(e);
    },
    hasTextFocus: () => t.hasTextFocus(),
    dispose: () => {
      t.dispose();
    }
  };
};
export {
  S as useEditor
};
