import tmp from 'tmp-promise';
import libre from 'libreoffice-convert';
import fs from 'node:fs/promises';
import { BuildBaseFileInputOutputModel, CALIBRE_INPUT_FORMAT_CONTENT_KEY, CALIBRE_OUTPUT_FORMAT_CONTENT_KEY, LIBRE_OFFICE_INPUT_FORMAT, LIBRE_OFFICE_OUTPUT_FORMAT, PANDOC_INPUT_FORMAT, PANDOC_OUTPUT_FORMAT, SlicePdfModel, buildCommandToConvertDocumentWithCalibre, buildCommandToConvertDocumentWithLibreOffice, buildCommandToConvertDocumentWithPandoc, buildCommandToGenerateLatexPdf, slicePdfUsingBytes, } from '../shared/index.js';
import { z } from 'zod';
import { buildUseConvert, buildUseSplit, transform_input_output_file_array, } from './base.js';
import _ from 'lodash';
import { handleCommand, } from './command.js';
// https://help.libreoffice.org/latest/en-US/text/shared/guide/convertfilters.html
export async function convertDocumentWithLibreOfficeNative({ inputData, format, }) {
    return new Promise((res, rej) => {
        libre.convert(Buffer.from(inputData), `.${format}`, undefined, (err, output) => {
            if (err) {
                return rej(err);
            }
            res(output);
        });
    });
}
// export async function splitPDF({ inputPath, outputDirectory }) {
//   let indices = []
//   let startPage = []
//   const data = fs.readFileSync(inputPath).buffer
//   const readPdf = await PDFDocument.load(data)
//   let endPage = readPdf.getPages().length
//   while (startPage < endPage) {
//     indices.push(startPage++)
//   }
//   fs.mkdir(outputDirectory, { recursive: true })
//   for (let i = 0, n = indices.length; i < n; i++) {
//     const index = indices[i]
//     const writePdf = await PDFDocument.create()
//     const [page] = await writePdf.copyPages(readPdf, [index])
//     writePdf.addPage(page)
//     const bytes = await writePdf.save()
//     fs.writeFileSync(
//       path.resolve(`${outputDirectory}/${i + 1}.pdf`),
//       bytes,
//     )
//   }
// }
// export async function readPDFMetadata({ inputPath }) {
//   const { PDFDocument } = require('pdf-lib')
//   const data = fs.readFileSync(inputPath).buffer
//   const pdfDoc = await PDFDocument.load(data, {
//     updateMetadata: false,
//   })
//   return {
//     title: pdfDoc.getTitle(),
//     author: pdfDoc.getAuthor(),
//     subject: pdfDoc.getSubject(),
//     creator: pdfDoc.getCreator(),
//     keywords: pdfDoc.getKeywords(),
//     producer: pdfDoc.getProducer(),
//     createdDate: pdfDoc.getCreationDate(),
//     updatedDate: pdfDoc.getModificationDate(),
//     pageCount: pdfDoc.getPages().length,
//   }
// }
// export async function updatePDFMetadata({
//   inputPath,
//   title,
//   author,
//   subject,
//   keywords,
//   producer,
//   creator,
//   createdDate,
//   updatedDate,
// }) {
//   const { PDFDocument } = require('pdf-lib')
//   const data = fs.readFileSync(inputPath).buffer
//   const pdfDoc = await PDFDocument.load(data)
//   if (title) {
//     pdfDoc.setTitle(title)
//   }
//   if (author) {
//     pdfDoc.setAuthor(author)
//   }
//   if (subject) {
//     pdfDoc.setSubject(subject)
//   }
//   if (keywords) {
//     pdfDoc.setKeywords(keywords)
//   }
//   if (producer) {
//     pdfDoc.setProducer(producer)
//   }
//   if (creator) {
//     pdfDoc.setCreator(creator)
//   }
//   if (createdDate) {
//     pdfDoc.setCreationDate(createdDate)
//   }
//   if (updatedDate) {
//     pdfDoc.setModificationDate(updatedDate)
//   }
//   const bytes = await pdfDoc.save()
//   fs.writeFileSync(inputPath, bytes)
// }
const IOPandoc = BuildBaseFileInputOutputModel.superRefine(transform_input_output_file_array(PANDOC_INPUT_FORMAT, PANDOC_OUTPUT_FORMAT));
export const useConvertDocumentWithPandoc = buildUseConvert(PANDOC_INPUT_FORMAT, PANDOC_OUTPUT_FORMAT, 'pandoc');
export async function convertDocumentWithPandoc(source) {
    const input = IOPandoc.parse(source);
    const list = buildCommandToConvertDocumentWithPandoc(input);
    for (const cmd of list) {
        await handleCommand(cmd);
    }
}
const IOLibreOffice = BuildBaseFileInputOutputModel.superRefine(transform_input_output_file_array(LIBRE_OFFICE_INPUT_FORMAT, LIBRE_OFFICE_OUTPUT_FORMAT));
export const useConvertDocumentWithLibreOffice = buildUseConvert(LIBRE_OFFICE_INPUT_FORMAT, LIBRE_OFFICE_OUTPUT_FORMAT, 'libre_office');
export async function convertDocumentWithLibreOffice(source) {
    const input = IOLibreOffice.parse(source);
    const list = buildCommandToConvertDocumentWithLibreOffice(input);
    for (const cmd of list) {
        await handleCommand(cmd);
    }
    // return input.output.file.path as string
}
const IOCalibre = BuildBaseFileInputOutputModel.superRefine(transform_input_output_file_array(CALIBRE_INPUT_FORMAT_CONTENT_KEY, CALIBRE_OUTPUT_FORMAT_CONTENT_KEY));
export const useConvertDocumentWithCalibre = buildUseConvert(CALIBRE_INPUT_FORMAT_CONTENT_KEY, CALIBRE_OUTPUT_FORMAT_CONTENT_KEY, 'calibre');
export async function convertDocumentWithCalibre(source) {
    const input = IOCalibre.parse(source);
    const list = buildCommandToConvertDocumentWithCalibre(input);
    for (const cmd of list) {
        await handleCommand(cmd);
    }
    return input.output.file.path;
}
const IOPdf = BuildBaseFileInputOutputModel.superRefine(transform_input_output_file_array(['pdf'], ['pdf']));
export const useSplitPdf = buildUseSplit(['pdf'], 'pdf_lib');
const IO = BuildBaseFileInputOutputModel.superRefine((v, ctx) => {
    if (!v.input.file.path.endsWith(`.tex`)) {
        ctx.addIssue({
            code: z.ZodIssueCode.custom,
            message: `Input path must have extension .tex`,
            path: ['input', 'file', 'path'],
        });
    }
    return v;
});
export async function convertDocumentWithPdfLatex(source) {
    const input = IO.parse(source);
    const tmpDirectory = await tmp.dir();
    const list = buildCommandToGenerateLatexPdf({
        ...input,
        output: {
            directory: tmpDirectory,
            file: {
                name: 'document',
            },
        },
    });
    for (const cmd of list) {
        await handleCommand(cmd);
    }
}
export async function convertLatexToHtml() {
    // htlatex file.tex
}
export async function slicePdf(source) {
    const input = SlicePdfModel.parse(source);
    const inputBuffer = await fs.readFile(input.input.file.path);
    const outputBuffer = await slicePdfUsingBytes(_.merge(input, {
        input: {
            file: {
                buffer: inputBuffer,
            },
        },
    }));
    await fs.writeFile(input.output.file.path, outputBuffer);
}
// https://html-validate.org/dev/running-in-browser.html
// https://github.com/apostrophecms/sanitize-html
//# sourceMappingURL=document.js.map