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


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

// This sample illustrates the basic text highlight capabilities of PDFNet.
// It simulates a full-text search engine that finds all occurrences of the word 'Federal'.
// It then highlights those words on the page.
//
// Note: The TextSearch class is the preferred solution for searching text within a single
// PDF file. TextExtractor provides search highlighting capabilities where a large number
// of documents are indexed using a 3rd party search engine.
((exports) => {

  exports.runHighlightsTest = async () => {
    const main = async () => {
      // eslint-disable-next-line no-unused-vars
      let ret = 0;

      // Relative path to the folder containing test files.
      const inputPath = '../TestFiles/';
      const outputPath = '../TestFiles/Output/';
      const inputFilename = 'paragraphs_and_tables.pdf';

      try {
        await PDFNet.startDeallocateStack();
        const doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + inputFilename);
        doc.initSecurityHandler();

        const page = await doc.getPage(1);

        if (page.id === '0') {
          console.log('Page not found.');
          return 1;
        }

        const txt = await PDFNet.TextExtractor.create();
        txt.begin(page);

        // Do not dehyphenate; that would interfere with character offsets
        const dehyphen = false;
        // Retrieve the page text
        const pageText = await txt.getAsText(dehyphen);
        
        // Simulating a full-text search engine that finds all occurrences of the word 'Federal'.
        // In a real application, plug in your own search engine here.
        const searchText = 'Federal';
        let charRanges = [];
        let ofs = pageText.indexOf(searchText);
        while (ofs >= 0) {
          const range = { index: ofs, length: searchText.length };
          charRanges.push(range); // character offset + length
          ofs = pageText.indexOf(searchText, ofs + 1);
        }

        // Retrieve Highlights object and apply annotations to the page
        const hlts = await txt.getHighlights(charRanges);
        await hlts.begin(doc);
        while ((await hlts.hasNext())) {
          const curPage = await doc.getPage((await hlts.getCurrentPageNumber()));
          const quadArr = await hlts.getCurrentQuads();
          for (let i = 0; i < quadArr.length; ++i) {
            const currQuad = quadArr[i];
            const x1 = Math.min(Math.min(Math.min(currQuad.p1x, currQuad.p2x), currQuad.p3x), currQuad.p4x);
            const x2 = Math.max(Math.max(Math.max(currQuad.p1x, currQuad.p2x), currQuad.p3x), currQuad.p4x);
            const y1 = Math.min(Math.min(Math.min(currQuad.p1y, currQuad.p2y), currQuad.p3y), currQuad.p4y);
            const y2 = Math.max(Math.max(Math.max(currQuad.p1y, currQuad.p2y), currQuad.p3y), currQuad.p4y);

            const highlight = await PDFNet.HighlightAnnot.create(doc, (await PDFNet.Rect.init(x1, y1, x2, y2)));
            await highlight.refreshAppearance();
            await curPage.annotPushBack(highlight);

            console.log('[' + x1.toFixed(2) + ', ' + y1.toFixed(2) + ', ' + x2.toFixed(2) + ', ' + y2.toFixed(2) + ']');
          }
          hlts.next();
        }

        // Output highlighted PDF doc
        await doc.save(outputPath + 'search_highlights.pdf', PDFNet.SDFDoc.SaveOptions.e_linearized);

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