import xml from "react-syntax-highlighter/dist/esm/languages/hljs/xml";
import { dracula } from "react-syntax-highlighter/dist/esm/styles/hljs";
import xmlFormat from "xml-formatter";

import { Light as SyntaxHighlighter } from "react-syntax-highlighter";
import { AsyncWidget } from "./AsyncWidget";
import React from "react";

SyntaxHighlighter.registerLanguage("xml", xml);

export function XMLWidget(p: { src: string }): React.ReactElement {
  const xml = xmlFormat(p.src);

  return (
    <SyntaxHighlighter
      language="xml"
      style={dracula}
      customStyle={{ fontSize: "120%" }}
    >
      {xml}
    </SyntaxHighlighter>
  );
}

export function XMLAsyncWidget(p: {
  identifier: string;
  load: () => Promise<string>;
  errMsg: string;
}): React.ReactElement {
  const [src, setSrc] = React.useState<string | undefined>();

  const load = async () => {
    setSrc(await p.load());
  };

  return (
    <AsyncWidget
      errMsg={p.errMsg}
      load={load}
      loadKey={p.identifier}
      build={() => <XMLWidget src={src!} />}
    />
  );
}
