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