import { JSONEditor } from "vanilla-jsoneditor";
import { useEffect, useRef } from "react";
import "./index.css";

export default function SvelteJSONEditor(props) {
  const refContainer = useRef(null);
  const refEditor = useRef(null);

  useEffect(() => {
    // create editor
    // console.log("create editor", refContainer.current);
    refEditor.current = new JSONEditor({
      target: refContainer.current,
      props: {},
    });

    return () => {
      // destroy editor
      if (refEditor.current) {
        // console.log("destroy editor");
        refEditor.current.destroy();
        refEditor.current = null;
      }
    };
  }, []);

  // update props
  useEffect(() => {
    if (refEditor.current && props) {
      // console.log("update props", props);
      refEditor.current.updateProps({
        ...props,
        content: {
          json: undefined,
          text: props.value || "",
        },
        onChange: (content) => {
          if (content.text !== undefined) {
            props.onChange(content.text);
          } else if (content.json !== undefined) {
            props.onChange(JSON.stringify(content.json));
          }
        },
      });
    }
  }, [props]);

  return (
    <div className="vanilla-jsoneditor-container">
      <div className="vanilla-jsoneditor-react" ref={refContainer}></div>
    </div>
  );
}
