// 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("@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/";

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();
