import { PDFDocument } from '@cantoo/pdf-lib';
import { registerFeature } from '../registry';
import { featureModal, pdfSource, footerButtons, deliver, type LoadedFile } from '../common';
import { bufferOf } from '../../core/util';
import { toast } from '../../ui/toast';
import { h } from '../../core/dom';

registerFeature({
  id: 'merge',
  title: 'Merge PDFs',
  desc: 'Combine several PDF files into a single document, in order.',
  icon: 'merge',
  category: 'organize',
  run(ctx) {
    let files: LoadedFile[] = [];
    const m = featureModal('Merge PDFs', 'Combine files into one — nothing is uploaded.', 'merge', 560);
    m.body.append(
      pdfSource(ctx, { multiple: true, onChange: (f) => { files = f; primary.disabled = files.length < 2; } }),
      h('p.hint', 'Files are merged in the order shown above.'),
    );
    const { primary } = footerButtons(m, 'Merge & download', async () => {
      if (files.length < 2) return;
      m.setBusy(true, 'Merging…');
      try {
        const out = await PDFDocument.create();
        for (const f of files) {
          const src = await PDFDocument.load(bufferOf(f.bytes), { ignoreEncryption: true });
          const pages = await out.copyPages(src, src.getPageIndices());
          pages.forEach((p) => out.addPage(p));
        }
        const bytes = await out.save({ useObjectStreams: true });
        m.close();
        deliver(bytes, 'merged.pdf');
      } catch (e) {
        m.setBusy(false);
        toast('Merge failed — one of the files may be damaged.', { type: 'error' });
        console.error(e);
      }
    }, 'merge');
    primary.disabled = true;
  },
});
