"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.postPDF = exports.executablePath = void 0;
const fs = require("fs");
const path = require("path");
const os = require("os");
const childProcess = require("child_process");
let platform = process.platform;
if (platform == "linux" && process.arch == "arm")
    platform += "_arm";
let executablePath = `${__dirname}/${platform}/postscriptum-postpdf`;
exports.executablePath = executablePath;
if (platform == "win32")
    exports.executablePath = executablePath += '.exe';
async function postPDF(pdfData, config, outputStream) {
    const tempDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'postscriptum-postpdf-'));
    const inputFile = path.resolve(tempDir, 'input.pdf');
    const configFile = path.resolve(tempDir, 'config.json');
    await Promise.all([fs.promises.writeFile(inputFile, pdfData), fs.promises.writeFile(configFile, JSON.stringify(config))]);
    return new Promise((resolve, reject) => {
        const postpdf = childProcess.spawn(executablePath, [inputFile, configFile, '-']);
        let errorOutput = "";
        postpdf.stderr.on('data', (data) => errorOutput += data);
        outputStream.on("error", reject);
        postpdf.on('close', (code, signal) => {
            fs.rmSync(tempDir, { recursive: true });
            if (code || signal || errorOutput)
                reject(new Error(`The post processing of the PDF did not stop correctly (${signal || code}):\n${errorOutput}`));
            else if (outputStream.writableFinished)
                resolve();
            else {
                outputStream.on('finish', resolve);
                outputStream.end();
            }
        });
        postpdf.stdout.pipe(outputStream);
    });
}
exports.postPDF = postPDF;
