import { wwwAPIPath } from "@/utilities/wwwAPI";
import { useTranslations } from "next-intl";

export const getHitTexts = (text: string) => {
  const pathBefore = window.location.href.substring(
    0,
    window.location.href.lastIndexOf("/"),
  );
  const textHtml = new DOMParser().parseFromString(text, "text/html");
  return Array.from(textHtml.getElementsByTagName("a"))
    .filter(({ href }) => href.startsWith(pathBefore))
    .map(({ href }) => href.substring(href.lastIndexOf("/") + 1));
};

export const tag = (
  t: ReturnType<typeof useTranslations<string>>,
  text: string,
  hits: { [fileName: string]: number },
  tagClass: string,
) => {
  const textHtml = new DOMParser().parseFromString(text, "text/html");
  Array.from(textHtml.getElementsByTagName("img")).forEach((tag) => {
    const src = tag.getAttribute("src");
    if (src?.includes("/") === false) {
      tag.src = `${wwwAPIPath}/file/${src}`;
      tag.className = tagClass;
    }
  });
  Array.from(textHtml.getElementsByTagName("audio")).forEach((tag) => {
    const src = tag.getAttribute("src");
    if (src?.includes("/") === false) {
      tag.src = `${wwwAPIPath}/file/${src}`;
      tag.className = tagClass;
    }
  });
  Array.from(textHtml.getElementsByTagName("video")).forEach((tag) => {
    const src = tag.getAttribute("src");
    if (src?.includes("/") === false) {
      tag.src = `${wwwAPIPath}/file/${src}`;
      tag.className = tagClass;
    }
  });
  Array.from(textHtml.getElementsByTagName("a")).forEach((tag) => {
    const href = tag.getAttribute("href");
    if (href?.includes("/") === false) {
      tag.href = `${wwwAPIPath}/file/${href}`;
      if (hits[href] >= 0) {
        tag.innerHTML += ` (${t("hitFileCount", { hit: hits[href] })})`;
      }
    }
  });
  return textHtml.body.innerHTML;
};
