// Copyright (C) 2003-2026, Foxit Software Inc..
// All Rights Reserved.
//
// http://www.foxitsoftware.com
//
// The following code is copyrighted and contains proprietary information and trade secrets of Foxit Software Inc..
// You cannot distribute any part of Foxit PDF SDK to any third party or general public,
// unless there is a separate license agreement with Foxit Software Inc. which explicitly grants you such rights.
//
// This file contains an example to demonstrate how to use Foxit PDF SDK to add, sign and verify paging seal signature
// in PDF document.

const FSDK = require("@fuxinsoft/foxit-pdf-sdk-node");
const fs = require('fs');
const os = require('os');
const path = require('path');
const util = require('util');


var sn = "Rew1vB0TqoMIxX444UcpScARWdhgJpsJfzmyMLR32a0+EgrCjp2NaQ==";
var key = "8f3g1sFttW8NAgfSNv+BvaJWy4Pp8flcm7ncNDkdvCCO4JwUFbGLyZdujReMaiplbYJwwxam3lr7uHtQaEf0xTSu8j2ZBdrZ8FS4OQkEUjOI9UEGb3Ic0GqmlP9T9OnSItOYqoZZA/OnYg5EaVP+c/ha32nUquOk+5riEdhYgINAZDdgJkPc+YSWsrfixOIROf6t34j3eRcyFnOY0MS7tSXi1AEPE0VZdyu+5bfmBSGvLI+WR5lQ+oOQR5hRGwqf990WEdBelNO7dxhZELVhEZ+/L60PpDf5y9A8qmrY6PiEU8nhqIyLpks0BxeIsYyZ3Cr82jjfbItPGyEARsIVzluBSgVMD4oGjojz8T6wGDEXUbmZH/pra94XAs8wZ28mzbmIEppWnhBqX0c6Ov8iXCfFfUZr4KNuPxMEgk4VOYTMOd70GEjGnylivw18hbn7ZpkWh2Zql+uU2HejvOgn+WHvT0HF9NhK0Xb5vH8aFkgBP92PJx8obIbxBVeeExczxvsqWufuPdXS2sPNIgMYZ2TtvqVVsiUToeGB2FQo09fzZOSH5Vi18u/siyvC3FmjeMf4+OYWPuDPNCcrb21NgcHam7XI8AAoGLTGtLLWR+fxynbBBcg2d2ZPcZ5CMFIfOBHRWCkcA0sDT3cl9nsBppHNJze/jVxHy+lREeQEA/etSIgohTGAWW3ZlpibRXqMxlmVWEPifCubbWTzQ6U54mRMpW2UghH3gvCNFNgdday3Av7EtlIJOdUuiMq3zmmd5J4Jt4C82CKnVewA0DtZ4EEtwRG9IYuLrfpuZlnjBAtoeXRV1lqUZ6BcCe0E3m9jO28sGkALuIeJQ74XG7X8lMC7lMWWQYiYD7D6G9QT6X3qV4vXJwNKRKpYc/rI+amEawTSnDYAMEaYPwtZ0rb/7BL+atsZZaI+ncebdfVfjDJZbCZAc+JnkuNlUn2xrNRuObw8h/G0lm2pNOEJ10S8R4+yplo5B1QmC2dCDhaTaW67QJPqnJPKbVmjw7i6KGBi+CDP3JnAKlOX/YUu8uk56JfeQUuGcQg/KaBMGctnchH2n1i3+oGbibhurQj22+OO66Q6mijKoCRP/QJm5WTGcO4c0iVX0B8dIlai/uv/pGU8Wps9MxysH5ViVIj56LWKuNfy1FNO9+wx4iHYnUxfW0Iccq3YJYAlOBkMv8VZIJl9aTEEFJ626LJEw/UbEBdR9CdlwnylPf4RuNW/lcGYMgq3xNVpp/bzYKwZivvQOFgMdX1tv8D33SHvAm3zrRCU+v94BJXnBi9k25fnKsc705IMwv+I6bueXA+mDnagj1oTqsWXZ0WnPAYI3WUO7sBf7XUH230wfYXnTSVhujJxiEP/2oWqi2813gtQkKwz9N2p6yT8Vsh3+BaAwwDvtOZMJKUFcabTBSL6NoouzmzwItJ4mIboT6KXaef66rs8jCU=";

const input_path = "../input_files/";
const output_path = "../output_files/";
const output_directory = output_path + "paging_seal_signature/";


// get current date time
function GetLocalDateTime() {
  const date = new Date();
  let timezone_hour = date.getTimezoneOffset() / 60 * -1;
  let timezone_minute = Math.abs(date.getTimezoneOffset() % 60);
  let datetime = new FSDK.DateTime(date.getFullYear(), date.getMonth() + 1, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds(), timezone_hour, timezone_minute);
  return datetime;
}
  
function DateTimeToString(datetime) {
  const pad = number => (number < 10 ? '0' + number : String(number));
  const offsetSign = datetime.utc_hour_offset >= 0 ? '+' : '-'; 
  const hourOffset = Math.abs(datetime.utc_hour_offset);
  const minuteOffset = Math.abs(datetime.utc_minute_offset);
  return `${pad(datetime.year)}/${pad(datetime.month)}/${pad(datetime.day)}-${pad(datetime.hour)}:${pad(datetime.minute)}:${pad(datetime.second)} ${offsetSign}${pad(hourOffset)}:${pad(minuteOffset)}`;
}
  
function TransformSignatureStateToString(sig_state) {
  let state_str;
  if (sig_state & FSDK.Signature.e_TypeUnknown)
    state_str += "Unknown";
  if (sig_state & FSDK.Signature.e_StateNoSignData) {
    if (state_str != "") state_str += "|";
    state_str += "NoSignData";
  }
  if (sig_state & FSDK.Signature.e_StateUnsigned) {
    if (state_str != "") state_str += "|";
    state_str += "Unsigned";
  }
  if (sig_state & FSDK.Signature.e_StateSigned) {
    if (state_str != "") state_str += "|";
    state_str += "Signed";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyValid) {
    if (state_str != "") state_str += "|";
    state_str += "VerfiyValid";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyInvalid) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyInvalid";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyErrorData) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyErrorData";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyNoSupportWay) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyNoSupportWay";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyErrorByteRange) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyErrorByteRange";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyChange) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyChange";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyIncredible) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyIncredible";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyNoChange) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyNoChange";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyIssueValid) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyIssueValid";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyIssueUnknown) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyIssueUnknown";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyIssueRevoke) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyIssueRevoke";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyIssueExpire) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyIssueExpire";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyIssueUncheck) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyIssueUncheck";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyIssueCurrent) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyIssueCurrent";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyTimestampNone) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyTimestampNone";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyTimestampDoc) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyTimestampDoc";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyTimestampValid) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyTimestampValid";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyTimestampInvalid) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyTimestampInvalid";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyTimestampExpire) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyTimestampExpire";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyTimestampIssueUnknown) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyTimestampIssueUnknown";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyTimestampIssueValid) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyTimestampIssueValid";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyTimestampTimeBefore) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyTimestampTimeBefore";
  }
  if (sig_state & FSDK.Signature.e_StateCertCannotGetVRI) {
    if (state_str != "") state_str += "|";
    state_str += "CertCannotGetVRI";
  }
  return state_str;
}

function AddPagingSealSiganture(pdf_doc, sub_filter, is_on_perforation) {
  let pdf_page = pdf_doc.GetPage(0);
  let page_width = pdf_page.GetWidth();
  let page_height = pdf_page.GetHeight();
  let sig_width =  page_width * 0.4;
  let sig_hegiht = page_height * 0.1;
  let range = new FSDK.Range(1, pdf_doc.GetPageCount(), FSDK.Range.e_All);
  let new_sig = pdf_doc.AddPagingSealSignature(range, sig_width, sig_hegiht, true);
  if (new_sig.IsEmpty()) return PagingSealSignature();
  
  let paging_seal_config = new FSDK.PagingSealConfig(FSDK.PagingSealConfig.e_PagingSealPositionLeft, page_width/2, 
      0.5, is_on_perforation, FSDK.PagingSealConfig.e_PagingSealStyleMultipleSignatures, false, 30);
  new_sig.SetPagingSealConfig(paging_seal_config);
    
  // Set values for the new signature.
  new_sig.SetKeyValue(FSDK.Signature.e_KeyNameSigner, "Foxit PDF SDK");
  let new_value = `As a sample for subfilter "${sub_filter}"`;
  new_sig.SetKeyValue(FSDK.Signature.e_KeyNameReason, new_value);
  new_sig.SetKeyValue(FSDK.Signature.e_KeyNameContactInfo, "support@foxitsoftware.com");
  new_sig.SetKeyValue(FSDK.Signature.e_KeyNameDN, "CN=CN,MAIL=MAIL@MAIL.COM");
  new_sig.SetKeyValue(FSDK.Signature.e_KeyNameLocation, "Fuzhou, China");
  new_value = `As a sample for subfilter "${sub_filter}"`;
  new_sig.SetKeyValue(FSDK.Signature.e_KeyNameText, new_value);
  let sign_time = GetLocalDateTime();
  new_sig.SetSignTime(sign_time);
  let image_file_path = input_path + "FoxitLogo.jpg";
  let image = new FSDK.Image(image_file_path);
  new_sig.SetImage(image, 0);
  // Set appearance flags to decide which content would be used in appearance.
  let ap_flags = FSDK.Signature.e_APFlagLabel | FSDK.Signature.e_APFlagSigner |
                      FSDK.Signature.e_APFlagReason | FSDK.Signature.e_APFlagDN |
                      FSDK.Signature.e_APFlagLocation | FSDK.Signature.e_APFlagText |
                      FSDK.Signature.e_APFlagSigningTime | FSDK.Signature.e_APFlagBitmap;
  new_sig.SetAppearanceFlags(ap_flags);
  let gaResult = new_sig.GenerateAppearance();
  return new_sig;
}

function AdobePPKLitePagingSealSignature(pdf_doc) {
  let filter = "Adobe.PPKLite";
  let sub_filter = "adbe.pkcs7.detached";

  console.log("Use signature callback object for filter \"%s\" and sub-filter \"%s\"",
    filter, sub_filter);
  // Add a new paging seal signature to the document.
  let is_on_perforation = false;
  let new_paging_seal_signature = AddPagingSealSiganture(pdf_doc, sub_filter, is_on_perforation);
  // Set filter and subfilter for the new  paging seal signature.
  new_paging_seal_signature.SetFilter(filter);
  new_paging_seal_signature.SetSubFilter(sub_filter);
  let is_signed = new_paging_seal_signature.IsSigned();
  let sig_state = new_paging_seal_signature.GetState();
  console.log("[Before signing] Signed?:%s\t State:%s",
          is_signed? "true" : "false",
          TransformSignatureStateToString(sig_state));

  // Sign the new signature.
  let signed_pdf_path = output_directory + "signed_left_paging_seal_signature_default_handler.pdf";
  let cert_file_path = input_path + "foxit_all.pfx";
  let cert_file_password = "123456";
  // Cert file path will be passed back to application through callback function FSSignatureCallback::Sign().
  // In this demo, the cert file path will be used for signing in callback function FSSignatureCallback::Sign().
  new_paging_seal_signature.StartSign(cert_file_path, cert_file_password,
                          FSDK.Signature.e_DigestSHA1, signed_pdf_path, null, null);
  console.log("[Sign] Finished!");
  is_signed = new_paging_seal_signature.IsSigned();
  sig_state = new_paging_seal_signature.GetState();
  console.log("[After signing] Signed?:%s\tState:%s",
          is_signed? "true" : "false",
          TransformSignatureStateToString(sig_state));

  // Open the signed document and verify the newly added paging seal signature (which is the last one).
  console.log("Signed PDF file: %s", signed_pdf_path);
  let signed_pdf_doc = new FSDK.PDFDoc(signed_pdf_path);
  let error_code = signed_pdf_doc.Load("");
  if (FSDK.e_ErrSuccess !=error_code ) {
    console.log("Fail to open the signed PDF file.");
    return;
  }
  // Get the last signature which is just added and signed.
  let sig_count = signed_pdf_doc.GetSignatureCount();
  let signed_signature = signed_pdf_doc.GetSignature(sig_count-1);
  // Verify the intergrity of signature.
  signed_signature.StartVerify(null, null);
  console.log("[Verify] Finished!");
  is_signed = signed_signature.IsSigned();
  sig_state = signed_signature.GetState();
  console.log("[After verifying] Signed?:%s\tState:%s",
          is_signed? "true" : "false",
          TransformSignatureStateToString(sig_state));
}

function CheckPagingSealSignatureInfo(pdf_doc) {
  let signature_count = pdf_doc.GetSignatureCount();
  if (signature_count<1) {
    console.log("No signature in current PDF file.");
    return;
  }
  for (let i = 0; i < signature_count; i++) {
    console.log("Signature index: %d", i);
    let signature = pdf_doc.GetSignature(i);
    if (signature.IsEmpty()) continue;
    let is_signed = signature.IsSigned();
    console.log("Signed?:%s", is_signed? "true":"false");
    let sig_state = signature.GetState();
    console.log("State:%s", TransformSignatureStateToString(sig_state));
  
    let widget_annot = signature.GetControl(0).GetWidget();
    console.log("Object number %d of related widget annotation's dictionary", widget_annot.GetDict().GetObjNum());
  
    let filter = signature.GetFilter();
    console.log("Filter:%s",filter);
    let sub_filter = signature.GetSubFilter();
    console.log("Sub-filter:%s", sub_filter);
    if (is_signed){
      let sign_time = signature.GetSignTime();
      let time_str = DateTimeToString(sign_time);
        console.log("Sign Time:%s", time_str);
    }
    let key_value;
    key_value = signature.GetKeyValue(FSDK.Signature.e_KeyNameSigner);
    console.log("Signer:%s", key_value);
    key_value = signature.GetKeyValue(FSDK.Signature.e_KeyNameLocation);
    console.log("Location:%s", key_value);
    key_value = signature.GetKeyValue(FSDK.Signature.e_KeyNameReason);
    console.log("Reason:%s", key_value);
    key_value = signature.GetKeyValue(FSDK.Signature.e_KeyNameContactInfo);
    console.log("Contact Info:%s", key_value);
    key_value = signature.GetKeyValue(FSDK.Signature.e_KeyNameDN);
    console.log("DN:%s", key_value);
    key_value = signature.GetKeyValue(FSDK.Signature.e_KeyNameText);
    console.log("Text:%s", key_value);
  }
}

let error_code = FSDK.Library.Initialize(sn, key);
if (FSDK.e_ErrSuccess != error_code) {
  if (FSDK.e_ErrInvalidLicense == error_code)
    console.log("[Failed] Current used Foxit PDF SDK key information is invalid.");
  else
    console.log("Library Initialize Error: %d", FSDK.e_ErrSuccess);
  return;
}

if (!fs.existsSync(output_directory)) {
  fs.mkdirSync(output_directory);
}

let input_file = input_path + "AboutFoxit.pdf";
console.log("Input file path: %s", input_file);
try {
  for (let i = 0; i < 1; i++) {
    let pdf_doc = new FSDK.PDFDoc(input_file);
    pdf_doc.StartLoad("", false, null);
    // Check information of existed signature(s) in PDF file if there's any signature in the PDF file.
    CheckPagingSealSignatureInfo(pdf_doc);
    // Add new signature, sign it and verify it with filter "Adobe.PPKLite" and different subfilter.
    let signed_pdf_path = output_directory + "signed_left_paging_seal_signature_default_handler.pdf";
    AdobePPKLitePagingSealSignature(pdf_doc);
    let pdf_doc1 = new FSDK.PDFDoc(signed_pdf_path);
    pdf_doc1.StartLoad("", false, null);
    CheckPagingSealSignatureInfo(pdf_doc1);
  }
} catch (e) {
  console.log(e);
}
FSDK.Library.Release();