import type { DocsExportSnapshot } from "@/lib/drive/docs-export-snapshot"
import { captureDocsPagesFromCanvas } from "@/lib/drive/docs-page-capture"
import { exportFileName } from "@/lib/drive/docs-export-download"

function downloadBlob(blob: Blob, fileName: string) {
  const url = URL.createObjectURL(blob)
  const anchor = document.createElement("a")
  anchor.href = url
  anchor.download = fileName
  anchor.click()
  URL.revokeObjectURL(url)
}

export async function exportDocsToPdf(snapshot: DocsExportSnapshot): Promise<void> {
  const canvases = await captureDocsPagesFromCanvas(snapshot, { scale: 2 })

  const [{ jsPDF }] = await Promise.all([import("jspdf")])

  const pageWidth = Number(
    snapshot.getPageStackElement()?.dataset.docsPageWidth ?? snapshot.pageLayout.widthPx
  )
  const pageHeight = Number(
    snapshot.getPageStackElement()?.dataset.docsPageHeight ?? snapshot.pageLayout.heightPx
  )

  const pdf = new jsPDF({
    orientation: pageWidth > pageHeight ? "landscape" : "portrait",
    unit: "mm",
    format: [
      snapshot.pageLayout.format.widthMm,
      snapshot.pageLayout.format.heightMm,
    ],
  })

  for (let pageIndex = 0; pageIndex < canvases.length; pageIndex += 1) {
    const imgData = canvases[pageIndex].toDataURL("image/jpeg", 0.92)
    if (pageIndex > 0) pdf.addPage()
    pdf.addImage(
      imgData,
      "JPEG",
      0,
      0,
      snapshot.pageLayout.format.widthMm,
      snapshot.pageLayout.format.heightMm
    )
  }

  const blob = pdf.output("blob")
  downloadBlob(blob, exportFileName(snapshot.sourceName, "pdf"))
}
