//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2026 by Apryse Software Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------

const fs = require('fs');
const { PDFNet } = require('@pdftron/pdfnet-node');
const PDFTronLicense = require('../LicenseKey/LicenseKey');

((exports) => {
  'use strict';

  //---------------------------------------------------------------------------------------
  // The Handwriting ICR Module is an optional PDFNet add-on that can be used to extract
  // handwriting from image-based pages and apply them as hidden text.
  //
  // The Apryse SDK Handwriting ICR Module can be downloaded from https://dev.apryse.com/
  //---------------------------------------------------------------------------------------
  exports.runHandwritingICRTest = () => {
    const main = async () => {
      try {
        // The location of the Handwriting ICR Module
        PDFNet.addResourceSearchPath('../Lib/');

        if (!(await PDFNet.HandwritingICRModule.isModuleAvailable())) {
          console.log('\nUnable to run HandwritingICRTest: Apryse SDK Handwriting ICR Module');
          console.log('not available.');
          console.log('---------------------------------------------------------------');
          console.log('The Handwriting ICR Module is an optional add-on, available for download');
          console.log('at https://dev.apryse.com/. If you have already downloaded this');
          console.log('module, ensure that the SDK is able to find the required files');
          console.log('using the PDFNet.addResourceSearchPath() function.\n');

          return;
        }

        // Relative path to the folder containing test files.
        const input_path = '../TestFiles/HandwritingICR/';
        const output_path = '../TestFiles/Output/';

        //--------------------------------------------------------------------------------
        // Example 1) Process a PDF without specifying options
        try {
          console.log('Example 1: processing icr.pdf');

          // Open the .pdf document
          const doc = await PDFNet.PDFDoc.createFromFilePath(input_path + 'icr.pdf');

          // Run ICR on the .pdf with the default options
          await PDFNet.HandwritingICRModule.processPDF(doc);

          // Save the result with hidden text applied
          await doc.save(output_path + 'icr-simple.pdf', PDFNet.SDFDoc.SaveOptions.e_linearized);
        } catch (err) {
          console.log(err);
        }

        //--------------------------------------------------------------------------------
/*
        // Example 2) Process a subset of PDF pages
        try {
          console.log('Example 2: processing pages from icr.pdf');

          // Open the .pdf document
          const doc = await PDFNet.PDFDoc.createFromFilePath(input_path + 'icr.pdf');

          // Process handwriting with custom options
          const options = await PDFNet.HandwritingICRModule.createHandwritingICROptions();

          // Optionally, process a subset of pages
          options.setPages("1-3");

          // Run ICR on the .pdf
          await PDFNet.HandwritingICRModule.processPDF(doc, options);

          // Save the result with hidden text applied
          await doc.save(output_path + 'icr-pages.pdf', PDFNet.SDFDoc.SaveOptions.e_linearized);
        } catch (err) {
          console.log(err);
        }
*/

        //--------------------------------------------------------------------------------
        // Example 3) Ignore zones specified for each page
        try {
          console.log('Example 3: processing & ignoring zones');

          // Open the .pdf document
          const doc = await PDFNet.PDFDoc.createFromFilePath(input_path + 'icr.pdf');

          // Process handwriting with custom options
          const options = await PDFNet.HandwritingICRModule.createHandwritingICROptions();

          // Process page 1 by ignoring the signature area on the bottom
          const ignore_zones_page1 = [];
          // These coordinates are in PDF user space, with the origin at the bottom left corner of the page.
          // Coordinates rotate with the page, if it has rotation applied.
          ignore_zones_page1.push(new PDFNet.Rect(78, 850.1 - 770, 340, 850.1 - 676));
          options.addIgnoreZonesForPage(ignore_zones_page1, 1);

          // Run ICR on the .pdf
          await PDFNet.HandwritingICRModule.processPDF(doc, options);

          // Save the result with hidden text applied
          await doc.save(output_path + 'icr-ignore.pdf', PDFNet.SDFDoc.SaveOptions.e_linearized);
        } catch (err) {
          console.log(err);
        }

        //--------------------------------------------------------------------------------
        // Example 4) The postprocessing workflow has also an option of extracting ICR results
        // in JSON format, similar to the one used by the OCR Module
        try {
          console.log('Example 4: extract & apply');

          // Open the .pdf document
          const doc = await PDFNet.PDFDoc.createFromFilePath(input_path + 'icr.pdf');

          // Extract ICR results in JSON format
          const json = await PDFNet.HandwritingICRModule.getICRJsonFromPDF(doc);
          fs.writeFileSync(output_path + "icr-get.json", json);

          // Insert your post-processing step (whatever it might be)
          // ...

          // Apply potentially modified ICR JSON to the PDF
          await PDFNet.HandwritingICRModule.applyICRJsonToPDF(doc, json);

          // Save the result with hidden text applied
          await doc.save(output_path + 'icr-get-apply.pdf', PDFNet.SDFDoc.SaveOptions.e_linearized);
        } catch (err) {
          console.log(err);
        }

        console.log('Done.');

      } catch (err) {
        console.log(err);
      }
    };
    PDFNet.runWithCleanup(main, PDFTronLicense.Key).catch(function(error) {
      console.log('Error: ' + JSON.stringify(error));
    }).then(function(){ return PDFNet.shutdown(); });
  };
  exports.runHandwritingICRTest();
})(exports);
// eslint-disable-next-line spaced-comment
//# sourceURL=HandwritingICRTest.js