import { jsPDF } from 'jspdf';

export default async function pdfGenerator(blobs: Blob[]) {
  const pdf = new jsPDF({
    unit: 'px',
    compress: true,
  });

  for (let i = 0; i < blobs.length; i++) {
    const blob = blobs[i];

    const imageUrl = URL.createObjectURL(blob);
    const img = new Image();
    img.src = imageUrl;

    await new Promise((resolve) => {
      img.onload = () => {
        const imgWidth = img.width;
        const imgHeight = img.height;

        const orientation = imgWidth > imgHeight ? 'landscape' : 'portrait';

        if (i === 0) {
          // Set ukuran dan orientasi halaman pertama
          (pdf as any).internal.pageSize.setWidth(imgWidth);
          (pdf as any).internal.pageSize.setHeight(imgHeight);
          pdf.setPage(1);
        } else {
          // Tambahkan halaman baru dengan ukuran dan orientasi yang sesuai
          pdf.addPage([imgWidth, imgHeight], orientation);
          pdf.setPage(pdf.getNumberOfPages());
        }

        pdf.addImage(img, 'PNG', 0, 0, imgWidth, imgHeight);
        resolve('');
      };
    });

    URL.revokeObjectURL(imageUrl);
  }

  pdf.save('downloaded-images.pdf');
}
