import { TFunction } from "i18next";
import { sprintf } from "sprintf-js";

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: TFunction,
  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 = `/www/file/${src}`;
      tag.className = tagClass;
    }
  });
  Array.from(textHtml.getElementsByTagName("audio")).forEach((tag) => {
    const src = tag.getAttribute("src");
    if (src?.includes("/") === false) {
      tag.src = `/www/file/${src}`;
      tag.className = tagClass;
    }
  });
  Array.from(textHtml.getElementsByTagName("video")).forEach((tag) => {
    const src = tag.getAttribute("src");
    if (src?.includes("/") === false) {
      tag.src = `/www/file/${src}`;
      tag.className = tagClass;
    }
  });
  Array.from(textHtml.getElementsByTagName("a")).forEach((tag) => {
    const href = tag.getAttribute("href");
    if (href?.includes("/") === false) {
      tag.href = `/www/file/${href}`;
      if (hits[href] >= 0) {
        tag.innerHTML += " " + sprintf(t("hitFileCount"), hits[href]);
      }
    }
  });
  return textHtml.body.innerHTML;
};
