import { PublicationAtom } from "@/recoil/atoms/publication";
import { useState, useEffect, useCallback, useRef } from "react";
import { useRecoilValue } from "recoil";
import { TTCQueryResolver } from "../ttcQuery/TTCResolvers";

export function Resolver({ resolver }: { resolver: string }) {
  const parser = useRecoilValue(PublicationAtom);
  const [res] = useState(new TTCQueryResolver(parser));
  const [content, setContent] = useState("");
  useEffect(() => {
    setContent(res.resolve(resolver));
  }, [resolver, res]);
  return <span>{content}</span>;
}

export function OnDemandResolver({
  resolver,
  template,
  title,
}: {
  resolver: string;
  template: string;
  title?: string;
}) {
  const parser = useRecoilValue(PublicationAtom);
  const res = useRef(new TTCQueryResolver(parser));
  const [content, setContent] = useState("");
  const generateContent = useCallback(() => {
    let content = template;
    const stackIdxs = Array.from(new Set(template.match(/\$\d/g)));
    for (const idx of stackIdxs) {
      let thing = res.current.getFromStack(idx);
      debugger;
      if (Array.isArray(thing)) thing = thing.at(0);
      if (typeof thing === "function") thing = thing();
      content = content.replaceAll(idx, thing as string);
    }
    setContent(content);
  }, [res, template]);

  const resolve = useCallback(() => {
    res.current.resolve(resolver, true);
    generateContent();
  }, [res, resolver, generateContent]);

  return (
    <>
      <button onMouseDown={() => setContent("")} onClick={resolve}>
        {title ?? "Resolve"}
      </button>
      <br />
      {!!content && <span>{content}</span>}
    </>
  );
}
