// 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 render all PDF layers of a PDF,
// and add layers in a 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 RenderPageToImage(page, layer_content, bitmap_file) {
  if (!page.IsParsed()) {
    // Parse page.
    page.StartParse(FSDK.PDFPage.e_ParsePageNormal, null, false);
  }

  let width = page.GetWidth();
  let height = page.GetHeight();
  let matrix = page.GetDisplayMatrix(0, 0, width, height, page.GetRotation());

  // Prepare a bitmap for rendering.
  let bitmap = new FSDK.Bitmap(width, height, FSDK.Bitmap.e_DIBArgb, null, 0);
  bitmap.FillRect(0xFFFFFFFF, null);

  // Render page.
  let render = new FSDK.Renderer(bitmap, false);

  if (!layer_content.IsEmpty()) {
    render.SetLayerContext(layer_content);
  }
  render.StartRender(page, matrix, null);
  let image = new FSDK.Image();
  image.AddFrame(bitmap);
  image.SaveAs(bitmap_file);
}

function UsgaeCodeToString(state) {
  switch (state) {
  case FSDK.LayerTree.e_StateON:
    return "ON";
  case FSDK.LayerTree.e_StateOFF:
    return "OFF";
  case FSDK.LayerTree.e_StateUnchanged:
    return "Unchanged";
  case FSDK.LayerTree.e_StateUndefined:
    return "Undefined";
  }
  return "Unknown";
}

function GetAllLayerNodesInformation(layer_node, depth, text_doc) {

  if (depth >= 0) {
    text_doc.WriteWithPrefix(depth, "\t", "%s", layer_node.GetName());
    if (layer_node.HasLayer()) {
      let state = layer_node.GetViewUsage();
      text_doc.Write(" %s\r\n", state == FSDK.LayerTree.e_StateON ? "[*]" : "[ ]");
      text_doc.WriteWithPrefix(depth, "\t", "View usage state:\t%s\r\n", UsgaeCodeToString(state));
      text_doc.WriteWithPrefix(depth, "\t", "Export usage state:\t%s\r\n", UsgaeCodeToString(layer_node.GetExportUsage()));

      let print_data = layer_node.GetPrintUsage();
      text_doc.WriteWithPrefix(depth, "\t", "Print usage state:\t%s, subtype: %s\r\n", UsgaeCodeToString(print_data.print_state),
        print_data.subtype);

      let zoom_data = layer_node.GetZoomUsage();
      text_doc.WriteWithPrefix(depth, "\t", `Zoom usage:\tmin_factor = ${zoom_data.min_factor.toFixed(4)} max_factor = ${zoom_data.max_factor.toFixed(4)}\r\n\r\n`);
    } else {
      text_doc.Write("\r\n");
    }
  }

  depth++;
  let count = layer_node.GetChildrenCount();
  for (let i = 0; i < count; i++) {
    let child = layer_node.GetChild(i);
    GetAllLayerNodesInformation(child, depth, text_doc);
  }
}

function SetAllLayerNodesInformation(layer_node) {
  if (layer_node.HasLayer()) {
    layer_node.SetDefaultVisible(true);
    layer_node.SetExportUsage(FSDK.LayerTree.e_StateUndefined);
    layer_node.SetViewUsage(FSDK.LayerTree.e_StateOFF);
    let print_data = new FSDK.LayerPrintData("subtype_print", FSDK.LayerTree.e_StateON);
    layer_node.SetPrintUsage(print_data);
    let zoom_data = new FSDK.LayerZoomData(1, 10);
    layer_node.SetZoomUsage(zoom_data);
    let new_name = "[View_OFF_Print_ON_Export_Undefined]" + layer_node.GetName();
    layer_node.SetName(new_name);
  }
  let count = layer_node.GetChildrenCount();
  for (let i = 0; i < count; i++) {
    let child = layer_node.GetChild(i);
    SetAllLayerNodesInformation(child);
  }
}

function SetAllLayerNodesVisible(context, layer_node, visible) {
  if (layer_node.HasLayer()) {
    context.SetVisible(layer_node, false);
  }
  let count = layer_node.GetChildrenCount();
  for (let i = 0; i < count; i++) {
    let child = layer_node.GetChild(i);
    SetAllLayerNodesVisible(context, child, visible);
  }
}

function RenderAllLayerNodes(doc, context, layer_node, pdf_name) {
  if (layer_node.HasLayer()) {
    context.SetVisible(layer_node, true);
    let page_count = doc.GetPageCount();
    for (let i=0; i<page_count; i++) {
      let page = doc.GetPage(i);
      let s = `${i}`;      
      let layer_name = layer_node.GetName();
      layer_name = layer_name.replace(/:/g, '');
      layer_name = layer_name.replace(/>/g, '');
      layer_name = layer_name.replace(/</g, '');
      layer_name = layer_name.replace(/=/g, '');
      let file_name = output_directory + "page_" + s + "_layer_node_" + layer_name + ".bmp";
      RenderPageToImage(page, context, file_name);
    }
  }

  let count = layer_node.GetChildrenCount();
  for (let i = 0; i < count; i++) {
    let child = layer_node.GetChild(i);
    RenderAllLayerNodes(doc,context,child,pdf_name);
  }
  if (layer_node.HasLayer()) {
    // The visibility of parent layer will affect the children layers,
    // so reset the visibility of parent layer after children have been rendered.
    context.SetVisible(layer_node, false);
  }
}

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 + "pdflayer/";
if (!fs.existsSync(output_directory))  {
  fs.mkdirSync(output_directory);
}

let input_file = input_path + "OCTest_src.pdf";
try {
  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", input_file, error_code);
    return;
  }
  let layertree = new FSDK.LayerTree(doc);
  let root = layertree.GetRootNode();
  if (root.IsEmpty()) {
    console.log("No layer information!\r\n");
    return;
  }

  // Get original information of all layer nodes.
  let file_info = output_directory + "original_layer_informations.txt";
  let original_doc = new TextDoc(file_info, "w");
  GetAllLayerNodesInformation(root, -1, original_doc);
  // Set new information.
  SetAllLayerNodesInformation(root);
  // Get new information.
  file_info = output_directory + "new_layer_informations.txt";
  let new_info = new TextDoc(file_info, "w");
  GetAllLayerNodesInformation(root, -1, new_info);

  let output_file = output_directory + "new_layers.pdf";
  doc.SaveAs(output_file, FSDK.PDFDoc.e_SaveFlagNormal);
  // Render layer node.
  let context = new FSDK.LayerContext(doc, FSDK.LayerContext.e_UsageView);
  SetAllLayerNodesVisible(context, root, false);

  RenderAllLayerNodes(doc, context, root, output_file);

// Edit layer tree
  doc = new FSDK.PDFDoc(input_file);
  error_code = doc.Load("");
  layertree = new FSDK.LayerTree(doc);
  root = layertree.GetRootNode();
  let children_count = root.GetChildrenCount();
  root.RemoveChild(children_count - 1);
  let child = root.GetChild(children_count - 2);
  let child0 = root.GetChild(0);
  child.MoveTo(child0, 0);
  child.AddChild(0, "AddedLayerNode", true);
  child.AddChild(0, "AddedNode", false);
  file_info = output_directory + "edit_layer_informations.txt";
  let edit_info = new TextDoc(file_info, "w");
  GetAllLayerNodesInformation(root, -1, edit_info);
  output_file = output_directory + "edit_layer_tree.pdf";
  doc.SaveAs(output_file, FSDK.PDFDoc.e_SaveFlagNormal);

// Create layer tree
  doc = new FSDK.PDFDoc(input_path + "AboutFoxit.pdf");
  error_code = doc.Load("");
  let has_layer = doc.HasLayer();
  layertree = new FSDK.LayerTree(doc);
  has_layer = doc.HasLayer();
  root = layertree.GetRootNode();
  let child_count = root.GetChildrenCount();
  root.AddChild(0, "AddedLayerNode", true);
  root.AddChild(0, "AddedNode", false);
  file_info = output_directory + "create_layer_informations.txt";
  let create_info = new TextDoc(file_info, "w");
  GetAllLayerNodesInformation(root, -1, create_info);
  output_file = output_directory + "create_layer_tree.pdf";
  doc.SaveAs(output_file, FSDK.PDFDoc.e_SaveFlagNormal);

  // Copy graphics objects from A PDF to B PDF
  doc = new FSDK.PDFDoc(input_file);
  error_code = doc.Load("");
  let page = doc.GetPage(0);
  page.StartParse(FSDK.PDFPage.e_ParsePageNormal, null, false);

  // Create layer tree
  let newdoc = new FSDK.PDFDoc(input_path + "SamplePDF.pdf");
  error_code = newdoc.Load("");
  let newpage = newdoc.GetPage(0);
  newpage.StartParse(FSDK.PDFPage.e_ParsePageNormal, null, false);
  has_layer = newdoc.HasLayer();
  layertree = new FSDK.LayerTree(newdoc);
  has_layer = newdoc.HasLayer();
  root = layertree.GetRootNode();
  child_count = root.GetChildrenCount();
  let node1 = root.AddChild(0, "AddedLayerNode", true);

  for (let i = 0; i < 5; i++)
  {
    let graphics_object = page.GetGraphicsObject(i);
    let ngraphics_object = graphics_object.Clone();
    newpage.InsertGraphicsObject(null, ngraphics_object);

    node1.AddGraphicsObject(newpage, ngraphics_object);
  }
  newpage.GenerateContent();

  output_file = output_directory + "copy_graphics_objects.pdf";
  newdoc.SaveAs(output_file, FSDK.PDFDoc.e_SaveFlagNormal);
  console.log("PDFLayer test.");

} catch (e) {
  console.log(e)
}
FSDK.Library.Release();