const div = document.getElementById("latex");
const temmlOptions = { displayMode: true, throwOnError: true };
const renderOptions = { pixelRatio: (window.devicePixelRatio ?? 1) + 0.5 };

if (window.chrome?.webview) {
  window.chrome.webview.addEventListener("message", onMessage);
} else {
  try {
    temml.render("y=\\sqrt{x^2-1}", div, temmlOptions);

    htmlToImage
      .toPng(div, renderOptions)
      .then(function (dataUrl) {
        var img = new Image();
        img.src = dataUrl;
        document.body.appendChild(img);
      })
      .catch(function (error) {
        console.error("oops, something went wrong!", error);
      });
  } catch (ex) {
    div.innerText = ex.toString();
    div.style.color = "#b22222";
    console.log(ex.toString());
  }
}

async function onMessage(e) {
  if (e.type == "message" && e.data) {
    const msg = e.data;
    if (msg.type == "append") {
      var managedHtml = ManageLatexContent(msg.msg);
      document.getElementById("container").innerHTML = `${managedHtml}`;
    } else if (msg.type == "fontSize") {
      document.getElementById("container").style.fontSize = `${msg.msg}`;
    }
  }
}

const LatexDictionary = {};

function ManageLatexContent(htmlStr) {
  console.log("htmlStr", htmlStr);
  var regexp = /(?:\${2} \[\]\s*([\s\S]*?)\s\${2} \[\]|\${2}\s*([\s\S]*?)\s*\${2})/gm;
  return htmlStr.replaceAll(regexp, (str, p1, p2) => {
    var htmlElement = document.createElement(null);
    var result = "";
    var findStr = p1 || p2;
    findStr = findStr
      .replaceAll(/<\/?em>/gm, "_")
      .replaceAll("&amp;", "&")
      .replaceAll("&gt;", ">")
      .replaceAll("&lt;", "<")
      .replaceAll(/ \\\s/gm, "\\\\");
    try {
      if (str in LatexDictionary) {
        result = LatexDictionary[str];
      }
      if (!result && result.length <= 0) {
        temml.render(findStr, htmlElement, { displayMode: p1 != null, throwOnError: true });
        result = htmlElement.getHTML();
        console.log(findStr, result);
        if (result && result.length > 0) {
          LatexDictionary[str] = result;
        }
      }
      if (result && result.length > 0) {
        return result;
      }
    } catch (ex) {
      console.error(ex);
    }
    return str;
  });
}
