// 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 call layout recognition related classes
// for PDF document.

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

var sn = "bPxThFlBAYifO3yiW0C51bKbjPap1zHaf5aG5sX378TjFvB7Q0802A==";
var key = "8f3g1sGNtR8NAgfSNv+BvaJWy2fnrw36NZvzh8GUxYXvs+/YczAk4e34yqlOnmL4asgxGMO7+rlOcSHUSSKagx5g4G7VEXfkYLXnDDx77FOOedZPrFFcOCu1vT4+wOKzy1zkORq9cKtiFf44byH5sfRqf+OvELjep2teT9eF9yPCsSw2vRKljXlPy40DMP9XX1O5OTe+mSG3RvwKUMb0+RpG3YobM87j+/ynTDlJMMXw4vgwuTb1ZuAtlvkTdFz7HDLV81C6TYnn73ddHeGD3qYWBVsD4uJkDwyyH/SWr7QX0HSgVg8HSZqnab1VGdAUYxKY2vGWeOTJdu6qDGb5ZEb9O3kZZg+9LYAmUKzDfCYwfIsYZ8Y9LPC4wMx70kIq7JpNnzPvigrdshV8/ew1F0+qP/P5Z1EB53vDVrp2LVSuL873Wv4g3PzjZlNH+1qgT87hC+Buto4qsSUfP5Y2z0uApu+c/TfttCXbeMLSsw9TY1HQD3mkrZExMaQqRrAuXAcZWdvBnVuG3DCZmm8q0DLxJiCfYfViAU/AkbeKMIGaTJdrvIXBcssfde4nmU6qr0M4x4+Hs2ESddtY2QRtLAUBq/7h7GJlJHkEZr8ueaUy/6D/2vvAWz6wMLgmjlPbDTLqzfnCJylHCPtcJmu1SPPT9v1VreBX3+zNWcIT8HueyHEiUniqzwWkRKaotrnNb/zhnHLPpgaBSwKjyi8rOzzVwu/nY84G9ye4jsVjmkIRItKDrW7z22iS+QQuTwfqLVuMB0OD4jMkPCC2slzPfEeZnuh4+Rewln2qLRJVgI72zJ20OBWAelGSpO1Ii2Y3gOvojdmtUwx6R3Z1qFNWTTB25o9ytcux8BLOtTCkA8T8xaT4N339OTCsu/TmfahIDixKvr8cDa6F2WkBT8SOfv64W9PgiNv5B/BMOD2VWYaAl0N7yD0NkYYg/cDWRC4dfpdeip1jrr0k3mND0oSpIkxC+FicZbaYYwRdtJ9OSVWJ5OE0voLv8HgLze8mw6s4TrN3z+a2NQCveMa2VRN7YcEF7agPrvb/qU+otMwHae/wM7+f+HFAaOW+WTfzfxIVFB8/A1DN0NiEX+em4G7nO5F5ZcvfYPpaaioe8Nn33BbVLtMjXqsOBeM8AXiVfpD6YO75j7BqnBUPnivvD8BxJaaIQZvVSuQmvGm0ynt03IYwE8Rq+jYsunvsZ86jh5BiUR+Nm7sK0Qe9BdZn/7jdqohMv9czfMGUAscX+xBMunFbDpcRbWVpUADcm209L8Ndek2XY7YlCMxPgPVNvfWRF2jxehib9Tpd7zB5ZIDfAEH9zrpLfp29DLvCh2Yx8mH7xxdKG1O9Q0GdHphYHhej6smAcPm68R0GUQaTOLfXqNpueGJC1GAOI3Y4swjyt7jMTWcibnKLzwukWE5rnEDhn5n64JnyUM0ZFkRmtOiV";

const input_path = "../input_files/";
const output_path = "../output_files/";

class TextDoc {
  constructor(file_name, file_mode) {
    this.file_name = file_name;
    this.file_mode = file_mode;
    this.file_stream = fs.openSync(file_name, file_mode);
    if (!this.file_stream) {
      throw new Error('Cannot open file');
    }
  }
  Write(format, ...args) {
    if(!this.file_stream) 
      throw new Error("File not opened");
    let formatted_string = util.format(format, ...args);
    let buffer = new Buffer.from(formatted_string, 'utf-8');
    fs.writeSync(this.file_stream, buffer, 0, buffer.length);
  }

  WriteWithPrefix(count, prefix, format, ...args){
    for (let i = 0; i < count; i++) {
      this.Write(prefix);
    }
    this.Write(format, ...args);
  }
  Close() {
    fs.closeSync(this.file_stream);
    this.file_stream = null;
  }
}

function GetChildFromElement(pElement, elemArray, nType) {  
  let nElemListSize = pElement.GetChildCount();
  for (let i = 0; i < nElemListSize; i++) {
    let item = pElement.GetChild(i);
    let item_type = item.GetElementType();
    if (item_type == nType) {
      elemArray.push(item);
    }      
    if (item.IsStructureElement()) {
      let srt_item = new FSDK.LRStructureElement(item);
      GetChildFromElement(srt_item, elemArray, nType);
    }
  }  
}

function LR_FormatBool(val) {
    return val ? "true" : "false"
}

function LR_FormatInt(val) {
  let s = `${val}`;
  return s;
}

function LR_FormatFloat(val) {
  return val.toFixed(1);
}

function LR_FormatStr(val) {
  return val
}
    
function LR_FormatARGB(val) {
  let r = (val >> 16) & 255;
  let g = (val >> 8) & 255;
  let b = val & 255;
  return '#' 
  + (r < 16 ? '0' : '') + r.toString(16) 
  + (g < 16 ? '0' : '') + g.toString(16) 
  + (b < 16 ? '0' : '') + b.toString(16);

}

function LR_FormatEnum(val) {
    return FSDK.LRStructureElement.StringifyEnumVariant(val)
}

function OutputLRStructureElement(element, doc, depth) {
  if (depth > 32)
    return;
  if (element.IsEmpty())
    return;
  
  let parentElement = element.GetParentElement();
  let bIsEmpty = parentElement.IsEmpty();

  let elemType = element.GetElementType();
  let elementTypeStr = FSDK.LRElement.StringifyElementType(elemType);
  let outputStr = "< StructureElement: " + elementTypeStr + " >\r\n";
  doc.WriteWithPrefix(depth, "\t", outputStr);
  let nSize = element.GetSupportedAttributeCount();
  for (let i = 0; i < nSize; i++) {
    let attrType = element.GetSupportedAttribute(i);
    let attrValueType = element.GetAttributeValueType(attrType);
    let nLength = 0;
    let bIsArray = FSDK.LRStructureElement.IsArrayAttributeValueType(attrValueType);
    nLength = element.GetAttributeValueCount(attrType);
    if (attrValueType == FSDK.LRStructureElement.e_AttributeValueTypeEmpty)
      continue;

    let szKey = FSDK.LRStructureElement.StringifyAttributeType(attrType);
    let szVal = "";
    if (bIsArray)
      szVal += "[";

    for (let idx = 0; idx < nLength; idx++) {
      if (idx)
        szVal += ", ";

      switch (attrValueType) {
        case FSDK.LRStructureElement.e_AttributeValueTypeEnum:
        case FSDK.LRStructureElement.e_AttributeValueTypeEnumArray:
          szVal += LR_FormatEnum(element.GetAttributeValueEnum(attrType, idx));
          break;
        case FSDK.LRStructureElement.e_AttributeValueTypeInt32:
        case FSDK.LRStructureElement.e_AttributeValueTypeInt32Array:
          szVal += LR_FormatInt(element.GetAttributeValueInt32(attrType, idx));
          break;
        case FSDK.LRStructureElement.e_AttributeValueTypeFloat:
        case FSDK.LRStructureElement.e_AttributeValueTypeFloatArray:
          szVal += LR_FormatFloat(element.GetAttributeValueFloat(attrType, idx));
          break;
        case FSDK.LRStructureElement.e_AttributeValueTypeARGB:
        case FSDK.LRStructureElement.e_AttributeValueTypeARGBArray:
          szVal += LR_FormatARGB(element.GetAttributeValueARGB(attrType, idx));
          break;
        case FSDK.LRStructureElement.e_AttributeValueTypeWStr:
        case FSDK.LRStructureElement.e_AttributeValueTypeWStrArray:
          szVal += LR_FormatStr(element.GetAttributeValueString(attrType, idx));
          break;
        default:
          break;
      }
    }
    if (bIsArray)
      szVal += "]";

    outputStr = szKey + ": " + szVal + "\r\n";
    doc.WriteWithPrefix(depth, "\t", outputStr);
  }
}

function OutputLRStructureElementWithGraphicsObject(element, doc, depth) {
  if (element.IsEmpty())
    return;

  let outputStr = "< LRGraphicsObjectElement: >\r\n";
  let parentPageObj = element.GetParentGraphicsObjectElement();
  let bIsEmpty = parentPageObj.IsEmpty();
  doc.WriteWithPrefix(depth, "\t", outputStr);
  let pageObj = element.GetGraphicsObject();
  let type = FSDK.GraphicsObject.e_TypeAll;
  if (pageObj != null)
    type = pageObj.GetType();
  let rcBox = element.GetBBox();
  let pDict = element.GetDict();
  let objIndex = element.GetGraphicsObjectIndex();
  let matrix = element.GetMatrix();   
  let szVal = `BBox: [${rcBox.left.toFixed(1)},${rcBox.top.toFixed(1)},${rcBox.right.toFixed(1)},${rcBox.bottom.toFixed(1)}]\r\n`;
  doc.WriteWithPrefix(depth, "\t", szVal);  
  szVal = `Matrix: [${matrix.a.toFixed(1)},${matrix.b.toFixed(1)},${matrix.c.toFixed(1)},${matrix.d.toFixed(1)},${matrix.e.toFixed(1)},${matrix.f.toFixed(1)}]\r\n`;
  doc.WriteWithPrefix(depth, "\t", szVal);  
  szVal = `PageObjectIndex: ${objIndex}\r\n`;
  doc.WriteWithPrefix(depth, "\t", szVal);

  let pObject = element.GetGraphicsObject();
  let text = (pObject && pObject.GetType() == FSDK.GraphicsObject.e_TypeText)
                     ? element.GetGraphicsObject().GetTextObject().GetText()
                     : "";
  if (text != "") {
    szVal = "Text: ";
    szVal += text;
    szVal += "\r\n";

    doc.WriteWithPrefix(depth, "\t", szVal);
  }
}

function OutputLRStructureElementWithContent(element, doc, depth) {
  if (element.IsEmpty())
    return;

  let pageObj = element.GetGraphicsObjectElement();
  let bIsEmpty = pageObj.IsEmpty();
  let parentPageObj = element.GetParentElement();
  bIsEmpty = parentPageObj.IsEmpty();

  let elemType = element.GetElementType();
  let elementTypeStr = FSDK.LRElement.StringifyElementType(elemType);
  let outputStr = "< LRContentElement: " + elementTypeStr + " >\r\n";
  doc.WriteWithPrefix(depth, "\t", outputStr);

  let rcBox = element.GetBBox();
  let nStartPos = 0, nLength = 0;
  let range = element.GetGraphicsObjectRange();
  if (!range.IsEmpty()) {
    nStartPos = range.GetSegmentStart(0);
    nLength = range.GetSegmentEnd(0) - nStartPos + 1;
  }
  let matrix = element.GetMatrix();

  let szVal = `BBox: [${rcBox.left.toFixed(1)},${rcBox.top.toFixed(1)},${rcBox.right.toFixed(1)},${rcBox.bottom.toFixed(1)}]\r\n`;

  doc.WriteWithPrefix(depth, "\t", szVal);
  szVal = `Matrix: [${matrix.a.toFixed(1)},${matrix.b.toFixed(1)},${matrix.c.toFixed(1)},${matrix.d.toFixed(1)},${matrix.e.toFixed(1)},${matrix.f.toFixed(1)}]\r\n`;
  doc.WriteWithPrefix(depth, "\t", szVal);
  szVal = `StartPos: ${nStartPos}\r\n`;
  doc.WriteWithPrefix(depth, "\t", szVal);
  szVal = `Length: ${nLength}\r\n`;
  doc.WriteWithPrefix(depth, "\t", szVal);

  if (!bIsEmpty)
  OutputLRStructureElementWithGraphicsObject(pageObj, doc, depth + 1);
}

function ShowLRElementInfo(element, doc, depth) {
  OutputLRStructureElement(element, doc, depth);
  let nElemListSize = element.GetChildCount();
  for (let i = 0; i < nElemListSize; i++) {
    let item = element.GetChild(i);
    let item_type = item.GetElementType();
    if (item.IsStructureElement()) {
      let srt_item = new FSDK.LRStructureElement(item);
      ShowLRElementInfo(srt_item, doc, depth + 1);
    } else if (item.IsContentElement()) {
      let srt_item = new FSDK.LRContentElement(item);
      OutputLRStructureElementWithContent(srt_item, doc, depth);
    } else if (item.IsGraphicsObjectElement()) {
      let srt_item = new FSDK.LRGraphicsObjectElement(item);
      OutputLRStructureElementWithGraphicsObject(srt_item, doc, depth);
    }
  }
}

function OutputAllLRElement(element, info_path) {
  text_doc = new TextDoc(info_path, "w");
  if (!element.IsEmpty()) {
    ShowLRElementInfo(element, text_doc, 0);
  } else {
    text_doc.Write("No layout recognition information!\r\n");
  }
}

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;
}

let output_directory = output_path + "layout_recognition/";
if (!fs.existsSync(output_directory))  {
  fs.mkdirSync(output_directory);
}

try {
  let input_file = input_path + "AboutFoxit.pdf";
  let info_file = output_directory + "layout_recognition_info.txt";

  let doc = new FSDK.PDFDoc(input_file);
  let error_code = doc.Load("");
  if (error_code != FSDK.e_ErrSuccess) {
    console.log("The Doc [%s] Error: %d\n", input_file, error_code);
    return;
  }
  let context = new FSDK.LRContext(doc.GetPage(0));

  let progressive = context.StartParse(null);

  let root = context.GetRootElement();
  let type = root.GetElementType();
  let nElemListSize = root.GetChildCount();
  console.log("RootElement GetChildCount: %d", nElemListSize);

  OutputAllLRElement(root, info_file);

  let element_array = [];
  GetChildFromElement(root, element_array, FSDK.LRElement.e_ElementTypeSpan);
  console.log("LRElement::e_ElementTypeSpan count: %d", element_array.length);
  console.log("Layout recognition test.");
} catch (e) {
  console.log(e);
}
FSDK.Library.Release();
