import { ref } from "vue";

export default function usePrint(THEAD_HEIGHT) {
  const buttonRef = ref(null);
  const A4_HEIGHT_MM = 297;
  const A4_HEIGHT_MM_TO_PX_PROPORTION = 3.78;
  let A4_HEIGHT_PX =
    A4_HEIGHT_MM * A4_HEIGHT_MM_TO_PX_PROPORTION - THEAD_HEIGHT;
  let elements = [];
  const printObj = {
    id: "printContent",
    closeCallback() {
      document.querySelector("#printContent").style.overflow = "hidden";
    },
  };
  const fnPrint = () => {
    document.querySelector("#printContent").style.overflow = "visible";
    elements = document.querySelectorAll("#printContent > table > tr");
    if (!document.querySelector("#printContent > table thead")) {
      A4_HEIGHT_PX = A4_HEIGHT_PX + THEAD_HEIGHT;
    }
    fnIsPaging();
    buttonRef.value.$el.click();
  };
  const fnIsPaging = (index = 0) => {
    for (let i = index; i < elements.length; i++) {
      if (
        elements[i].offsetHeight +
          elements[i].offsetTop -
          elements[index].offsetTop >=
        A4_HEIGHT_PX
      ) {
        elements[i - 1].setAttribute("style", "page-break-after: always;");
        fnIsPaging(i === index ? i + 1 : i);
        break;
      }
    }
  };

  return { fnPrint, printObj, buttonRef };
}
