// 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 get/set attributes of viewer preference
// and values of metadata in a PDF file.

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 DateTimeToString(datetime) {
  const pad = number => String(number).padStart(2, '0');
  const offsetSign = datetime.utc_hour_offset >= 0 ? '+' : '-'; 
  const hourOffset = Math.abs(datetime.utc_hour_offset);
  const minuteOffset = Math.abs(datetime.utc_minute_offset);
  return `${pad(datetime.year)}/${pad(datetime.month)}/${pad(datetime.day)}-${pad(datetime.hour)}:${pad(datetime.minute)}:${pad(datetime.second)} ${offsetSign}${pad(hourOffset)}:${pad(minuteOffset)}`;
}

// get current date time
function GetLocalDateTime() {
  const date = new Date();
  let timezone_hour = date.getTimezoneOffset() / 60 * -1;
  let timezone_minute = Math.abs(date.getTimezoneOffset() % 60);
  let datetime = new FSDK.DateTime(date.getFullYear(), date.getMonth() + 1, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds(), timezone_hour, timezone_minute);
  return datetime;
}

const kUIItems = [
  FSDK.DocViewerPrefs.e_HideToolbar, FSDK.DocViewerPrefs.e_HideMenubar,
  FSDK.DocViewerPrefs.e_HideWindowUI, FSDK.DocViewerPrefs.e_FitWindow,
  FSDK.DocViewerPrefs.e_CenterWindow, FSDK.DocViewerPrefs.e_DisplayDocTitle ];

const kDisplayModes = [ FSDK.PDFDoc.e_DisplayUseNone,   FSDK.PDFDoc.e_DisplayUseOutlines,
                        FSDK.PDFDoc.e_DisplayUseThumbs, FSDK.PDFDoc.e_DisplayFullScreen,
                        FSDK.PDFDoc.e_DisplayUseOC,     FSDK.PDFDoc.e_DisplayUseAttachment ];

const kDisplayModeStrings = ["UseNone", "UseOutlines", "UseThumbs", "FullScreen", "UseOC", "UseAttachment" ];

const kBoxItemStrings = ["ViewArea", "ViewClip", "PrintArea", "PrintClip"];
function GetPageBoxName(type){
  switch (type) {
  case FSDK.PDFPage.e_MediaBox:
    return "MediaBox";
  case FSDK.PDFPage.e_CropBox:
    return "CropBox";
  case FSDK.PDFPage.e_TrimBox:
    return "TrimBox";
  case FSDK.PDFPage.e_ArtBox:
    return "ArtBox";
  case FSDK.PDFPage.e_BleedBox:
    return "BleedBox";
  }
  return "";
}

function GetViewerPrefName(ui_item) {
  switch(ui_item){
  case FSDK.DocViewerPrefs.e_HideToolbar:
    return "HideToolbar";
  case FSDK.DocViewerPrefs.e_HideMenubar:
    return "HideMenubar";
  case FSDK.DocViewerPrefs.e_HideWindowUI:
    return "HideWindowUI";
  case FSDK.DocViewerPrefs.e_FitWindow:
    return "FitWindow";
  case FSDK.DocViewerPrefs.e_CenterWindow:
    return "CenterWindow";
  case FSDK.DocViewerPrefs.e_DisplayDocTitle:
    return "DisplayDocTitle";
  }
  return "";
}

function GetViewerPrefPrintScaleName(ui_item) {
  switch(ui_item) {
  case FSDK.DocViewerPrefs.e_PrintScaleNone:
    return "PrintScaleNone";
  case FSDK.DocViewerPrefs.e_PrintScaleAppDefault:
    return "PrintScaleAppDefault";
  }
  return "";
}

function ShowDocViewerPrefsInfo(doc, file_name) {
  file_info = output_directory + "DocViewerPrefsInfo_"+ file_name;
  let text_doc = new TextDoc(file_info, "w");

  let prefs = new FSDK.DocViewerPrefs(doc, null);
  text_doc.Write("Document viewer preferences information:\r\n");
  // Get UI visibility status.
  for (let i = 0; i < kUIItems.length; i++) {
      text_doc.Write("Visibility of %s:\t%s\r\n", GetViewerPrefName(kUIItems[i]), prefs.GetUIDisplayStatus(kUIItems[i]) ? "Yes" : "No");
  }
  // Get display mode for non full-screen mode.
  let mode = prefs.GetNonFullScreenPageMode();
  let display_mode;
  for (let i = 0; i < kDisplayModes.length; i++) {
    if (mode == kDisplayModes[i]) {
      display_mode = kDisplayModeStrings[i];
      break;
    }
  }
  text_doc.Write("None full screen page mode:\t%s\r\n", display_mode);
  // Get reading direction.
  text_doc.Write("Reading direction:\t%s\r\n", prefs.GetReadingDirection() ? "left to right" : "right to left");
  // Get the type of area item.
  type = prefs.GetPrintClip();
  text_doc.Write("The GetPrintClip returned:\t%s\r\n", GetPageBoxName(type));
  type = prefs.GetPrintArea();
  text_doc.Write("The GetPrintArea returned:\t%s\r\n", GetPageBoxName(type));
  type = prefs.GetViewArea();
  text_doc.Write("The GetViewArea returned:\t%s\r\n", GetPageBoxName(type));
  type = prefs.GetViewClip();
  text_doc.Write("The GetViewClip returned:\t%s\r\n", GetPageBoxName(type));

  // Get page scaling option.
  text_doc.Write("Page scaling option:\t%s\r\n", GetViewerPrefPrintScaleName(prefs.GetPrintScale()));
  // Get the number of copies to be printed.
  text_doc.Write("The number of copies to be printed:\t%d\r\n", prefs.GetPrintCopies());
  // Get page ranges which allowed to print
  text_doc.Write("Page ranges for printing:\r\n");
  print_ranges = prefs.GetPrintRange();
  if(!print_ranges.IsEmpty())
  {
    for (let i = 0; i < print_ranges.GetSegmentCount(); i=i+1)
      text_doc.Write("\tfirst:\t%d\tlast:\t%d\r\n", print_ranges.GetSegmentStart(i), print_ranges.GetSegmentEnd(i));

  }
}

function SetDocViewerPrefsInfo(doc) {
  doc.SetDisplayMode(FSDK.PDFDoc.e_DisplayFullScreen);
  let prefs = new FSDK.DocViewerPrefs(doc, null);
  // Set UI visibility status.
  for (let i = 0; i < kUIItems.length; i++) {
    prefs.SetUIDisplayStatus(kUIItems[i], true);
  }
  // Set display mode for non full-screen mode.
  prefs.SetNonFullScreenPageMode(FSDK.PDFDoc.e_DisplayUseOutlines);
  // Set reading direction.
  prefs.SetReadingDirection(false);
  // Set the type of area item.

  prefs.SetViewArea(FSDK.PDFPage.e_CropBox);
  prefs.SetViewClip(FSDK.PDFPage.e_CropBox);
  prefs.SetPrintArea(FSDK.PDFPage.e_CropBox);
  prefs.SetPrintClip(FSDK.PDFPage.e_CropBox);
  // Set page scaling option.
  prefs.SetPrintScale(FSDK.DocViewerPrefs.e_PrintScaleNone);
  // Set the number of copies to be printed.
  prefs.SetPrintCopies(4);
  let print_range = new FSDK.Range(0, doc.GetPageCount() / 2, FSDK.Range.e_All);
  prefs.SetPrintRange(print_range);
}

let kMetadataItems = [ "Title", "Author", "Subject", "Keywords",
    "Creator", "Producer", "CreationDate", "ModDate" ];

function ShowMetaDataInfo(doc, file_name) {
  let output_file = output_directory + "MetaDataInfo_"+file_name;
  text_doc = new TextDoc(output_file, "w");
  text_doc.Write("Metadata information:\r\n");
  metadata = new FSDK.Metadata(doc);
  for (let i = 0; i < kMetadataItems.length; i++) {
    let item = kMetadataItems[i];
    text_doc.Write("%s: ", item);
    let value = metadata.GetValues(item);
    for(let j=0;j<value.GetSize();j++)
    {
      text_doc.Write("%s", value.GetAt(j));
    }
    text_doc.Write("\r\n");
  }
}

function SetMetaDataInfo(doc) {
  let kMetadataValues = ["Title set by simple demo", "Simple demo",
    "Subject set by simple demo", "Keywords set by simple demo",
    "Foxit PDF SDK", "Foxit" ];
  let metadata = new FSDK.Metadata(doc);
  for (let i = 0; i < kMetadataValues.length; i++) {
    MetadataValues = new FSDK.WStringArray() ;
    MetadataValues.Add(kMetadataValues[i]);
    metadata.SetValues(kMetadataItems[i], MetadataValues);
  }
  metadata.SetCreationDateTime(GetLocalDateTime());
  metadata.SetModifiedDateTime(GetLocalDateTime());
}


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 + "docinfo/";

if (!fs.existsSync(output_directory)) {
  fs.mkdirSync(output_directory);
}
try {
  let input_file = input_path + "AboutFoxit.pdf";
  let doc = new FSDK.PDFDoc(input_file);
  let code = doc.Load("");
  if (code != FSDK.e_ErrSuccess) {
    console.log("[Failed] Cannot load PDF document %s.\r\nError Message: %d\r\n", input_file, code);
    return 1;
  }

  // Show original information.
  ShowDocViewerPrefsInfo(doc,"original.txt");
  ShowMetaDataInfo(doc,"original.txt");

  // Set information.
  SetDocViewerPrefsInfo(doc);
  SetMetaDataInfo(doc);

  // Show new information.
  ShowDocViewerPrefsInfo(doc,"new.txt");
  ShowMetaDataInfo(doc,"new.txt");
  output_file = output_directory + "AboutFoxit_docinfo.pdf";
  doc.SaveAs(output_file, FSDK.PDFDoc.e_SaveFlagNoOriginal);
} catch (e) {
  console.log(e)
}
FSDK.Library.Release();
