"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TimestampAndEnableLTV = void 0;
const TimestampAndEnableLTV = (docBuffer, certPath, certTSAUrl, imgBytes, coords, lib) => __awaiter(void 0, void 0, void 0, function* () {
    const doc = yield lib.PDFDoc.createFromBuffer(docBuffer);
    doc.initSecurityHandler();
    const tst_config = yield lib.TimestampingConfiguration.createFromURL(certTSAUrl);
    const opts = yield lib.VerificationOptions.create(lib.VerificationOptions.SecurityLevel.e_compatibility_and_archiving);
    if (typeof certPath === "string") {
        yield opts.addTrustedCertificateUString(certPath);
    }
    else {
        yield opts.addTrustedCertificate(certPath);
    }
    const img = yield lib.Image.createFromMemory2(doc, imgBytes);
    //make this dynamic with canvas lib
    const imgWidth = 300;
    const imgHeight = 300;
    const pagesForSining = Object.keys(coords).map((k) => {
        return parseInt(k);
    });
    const pages = yield doc.getPageCount();
    let result;
    for (let p = 1; p <= pages; p++) {
        if (!pagesForSining.includes(p)) {
            continue;
        }
        const page = yield doc.getPage(p);
        const doctimestamp_signature_field = yield doc.createDigitalSignatureField();
        const widgetAnnot = yield lib.SignatureWidget.createWithDigitalSignatureField(doc, new lib.Rect(parseFloat(coords[p].x), parseFloat(coords[p].x + imgWidth), parseFloat(coords[p].y), parseFloat(coords[p].y + imgHeight)), doctimestamp_signature_field);
        yield page.annotPushBack(widgetAnnot);
        yield widgetAnnot.createSignatureAppearance(img);
        yield doctimestamp_signature_field.timestampOnNextSave(tst_config, opts);
        result = yield doc.saveMemoryBuffer(lib.SDFDoc.SaveOptions.e_incremental);
    }
    return result.buffer;
});
exports.TimestampAndEnableLTV = TimestampAndEnableLTV;