import { InvoiceTemplate } from '../invoice.template';
import * as PdfPrinter from 'pdfmake';
import { PassThrough } from 'stream';

export async function GeneratePdf(transaction, invoiceType, banks) {
  const fonts = {
    Roboto: {
      normal: './assets/fonts/Roboto-Regular.ttf',
      bold: './assets/fonts/Roboto-Medium.ttf',
      italics: './assets/fonts/Roboto-Italic.ttf',
      bolditalics: './assets/fonts/Roboto-MediumItalic.ttf',
    },
  };

  const printer = new PdfPrinter(fonts);

  const docDefinition = InvoiceTemplate(transaction, invoiceType, banks);

  const createPdfBuffer = (docDefinition) => {
    return new Promise((resolve, reject) => {
      const pdfDoc = printer.createPdfKitDocument(docDefinition);
      const chunks = [];
      const stream = new PassThrough();

      pdfDoc.pipe(stream);
      pdfDoc.end();

      stream.on('data', (chunk) => {
        chunks.push(chunk);
      });

      stream.on('end', () => {
        const pdfBuffer = Buffer.concat(chunks);
        resolve(pdfBuffer);
      });

      stream.on('error', reject);
    });
  };

  const pdfBuffer = await createPdfBuffer(docDefinition);
  return pdfBuffer;
}
