// 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 create or open a portfolio PDF file.

import com.foxit.sdk.PDFException;
import com.foxit.sdk.common.Library;
import com.foxit.sdk.pdf.PDFDoc;
import com.foxit.sdk.pdf.Portfolio;
import com.foxit.sdk.pdf.SchemaField;
import com.foxit.sdk.pdf.SchemaFieldArray;
import com.foxit.sdk.pdf.PortfolioNode;
import com.foxit.sdk.pdf.PortfolioNodeArray;
import com.foxit.sdk.pdf.PortfolioFileNode;
import com.foxit.sdk.pdf.PortfolioFolderNode;
import com.foxit.sdk.pdf.FileSpec;
import com.foxit.sdk.common.Constants;
import com.foxit.sdk.common.DateTime;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class portfolio {
    private static String 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=";
    private static String sn = "Rew1vB0TqoMIxX444UcpScARWdhgJpsJfzmyMLR32a0+EgrCjp2NaQ==";
    private static String output_path = "../output_files/portfolio/";
    private static String input_path = "../input_files/";

    // You can also use System.load("filename") instead. The filename argument must be an absolute path name.
    static {
       String os = System.getProperty("os.name").toLowerCase();
       String lib = "fsdk_java_";
       if (os.startsWith("win")) {
           lib += "win";
       } else if (os.startsWith("mac")) {
          lib += "mac";
       } else {
           lib += "linux";
       }
        
       if (System.getProperty("sun.arch.data.model").equals("64")) {
        if(System.getProperty("os.arch").equals("aarch64")){
          if(os.startsWith("mac")){
             lib += "arm";
           }
           else{
             lib += "armv8";
           }
         }
         else{
            lib += "64";
         }
        } else {
         if(System.getProperty("os.arch").equals("arm")){
            lib += "armv7";
         }
         else{
            lib += "32";
         }
       }
       System.loadLibrary(lib);
    }

    private static void createResultFolder(String output_path) {
        File myPath = new File(output_path);
        if (!myPath.exists()) {
            myPath.mkdir();
        }
    }
    
    private static boolean creatPortfolioPDF(String saved_portfolio_pdf_path) throws PDFException {
        // Create a new blank portfolio PDF.
        Portfolio new_portfolio = Portfolio.createPortfolio();
        if (true == new_portfolio.isEmpty()) {
            System.out.println("[FAILED] Fail to create a new portfolio PDF.\r\n");
            return false;
        }

        // Get the root node.
        PortfolioNode root_node = new_portfolio.getRootNode();
        if (true == root_node.isEmpty()) {
            System.out.println("[FAILED] Fail to get the root node.\r\n");
            return false;
        }
        // The root node should be a folder node, so transfer to use PortfolioFolderNode.
        PortfolioFolderNode root_folder = new PortfolioFolderNode(root_node);

        // Pre-load the PDF file which is to be added to new sub folder in portfolio PDF.
        // ATTENTION: please keep the PDF document object valid until portfolio PDF is saved or ends its life-cycle.
        String input_pdf_filename = "AboutFoxit.pdf";
        String input_pdf_file_path = input_path + input_pdf_filename;
        PDFDoc pdf_doc = new PDFDoc(input_pdf_file_path);
        int error_code = pdf_doc.load(null);
        if (error_code != Constants.e_ErrSuccess) {
            System.out.println(String.format("[FAILED] Fail to load PDF file %s. Error: %d\n", input_pdf_file_path, error_code));
        }

        // Add a sub folder to root folder node.
        PortfolioFolderNode new_sub_foldernode = root_folder.addSubFolder("Sub Folder-1");
        if (true == new_sub_foldernode.isEmpty()) {
            System.out.println("[FAILED] Fail to add sub folder.\r\n");
        } else {
            new_sub_foldernode.setDescription("This is a sub folder added to portfolio PDF file.");

            if (false == pdf_doc.isEmpty()) {
                // Add a valid PDF document object to current folder node.
                // ATTENTION: please keep the PDF document object valid until portfolio PDF is saved or ends its life-cycle.
                PortfolioFileNode new_filenode = new_sub_foldernode.addPDFDoc(pdf_doc, input_pdf_filename);
                if (true == new_filenode.isEmpty()) {
                    System.out.println(String.format("[FAILED] Fail to add PDF file %s.\r\n", input_pdf_file_path));
                } else {
                    FileSpec file_spec = new_filenode.getFileSpec();
                    file_spec.setDescription("This is a common PDF file added to portfolio PDF file");
                }
            }
        }

        // Add a non-PDF file to root folder node.
        String input_file_path = input_path + "FoxitLogo.jpg";
        PortfolioFileNode new_sub_filenode = root_folder.addFile(input_file_path);
        if (true == new_sub_filenode.isEmpty()) {
            System.out.println(String.format("[FAILED] Fail to add file %s.\r\n", input_file_path));
        } else {
            FileSpec file_spec = new_sub_filenode.getFileSpec();
            file_spec.setDescription("This is a non-PDF file added to portfolio PDF file.");
        }
  
        // User can update schema field and other properties by class Portfolio, if necessary.
  
        // Save the new portfolio PDF file.
        PDFDoc portfolio_pdf_doc = new_portfolio.getPortfolioPDFDoc();
        if (true == portfolio_pdf_doc.isEmpty()) {
            System.out.println("[FAILED] Fail to get portfolio PDF document object.\r\n");
            return false;
        } else {
            return portfolio_pdf_doc.saveAs(saved_portfolio_pdf_path, PDFDoc.e_SaveFlagNormal);
        }
    }

    private static void outputTab(FileWriter output_txt_doc, int nTabCount) throws IOException, PDFException {
        for (int i = 0; i<nTabCount; i++)
            output_txt_doc.write("\t");
    }

    private static void outputFileNodeInfo(FileWriter output_txt_doc, PortfolioFileNode node, int tab_count) throws IOException, PDFException {
        if (tab_count>0)
            outputTab(output_txt_doc, tab_count);
        output_txt_doc.write("Type:File\r\n");

        String key_name = node.getKeyName();
        if (tab_count>0)
            outputTab(output_txt_doc, tab_count);
        output_txt_doc.write(String.format("Key Name:%s\r\n", key_name));

        FileSpec file_spec = node.getFileSpec();
        String file_name = file_spec.getFileName();
        if (tab_count>0)
            outputTab(output_txt_doc, tab_count);
        output_txt_doc.write(String.format("File Name:%s\r\n", file_name));

        String description = file_spec.getDescription();
        if (tab_count>0)
            outputTab(output_txt_doc, tab_count);
        output_txt_doc.write(String.format("Description:%s\r\n", description));
    }

    private static void outputFolderNodeInfo(FileWriter output_txt_doc, PortfolioFolderNode node, int tab_count) throws IOException, PDFException {
        if (tab_count>0)
            outputTab(output_txt_doc, tab_count);
        output_txt_doc.write("Type:Folder\r\n");

        String name = node.getName();
        if (tab_count>0)
            outputTab(output_txt_doc, tab_count);
        output_txt_doc.write(String.format("Name:%s\r\n", name));

        String description = node.getDescription();
        if (tab_count>0)
            outputTab(output_txt_doc, tab_count);
        output_txt_doc.write(String.format("Description:%s\r\n", description));

        PortfolioNodeArray sub_nodes = node.getSortedSubNodes();
        outputSubNodesInfo(output_txt_doc, sub_nodes, tab_count + 1);
    }

    private static void outputNodeInfo(FileWriter output_txt_doc, PortfolioNode node, int tab_count) throws IOException, PDFException {
        switch (node.getNodeType()) {
            case PortfolioNode.e_TypeFolder:
                outputFolderNodeInfo(output_txt_doc, new PortfolioFolderNode(node), tab_count);
                break;
            case PortfolioNode.e_TypeFile:
                outputFileNodeInfo(output_txt_doc, new PortfolioFileNode(node), tab_count);
                break;
            default:
                break;
        }
    }

    private static void outputSubNodesInfo(FileWriter output_txt_doc, PortfolioNodeArray sub_nodes, int tab_count) throws IOException, PDFException {
        for (int index = 0; index < sub_nodes.getSize(); index++) {
            if (tab_count > 0)
                outputTab(output_txt_doc, tab_count);
            output_txt_doc.write(String.format("Sorted Index (under current folder):%d\r\n", index));
            outputNodeInfo(output_txt_doc, sub_nodes.getAt(index), tab_count);
            output_txt_doc.write("========\r\n");
        }
    }

    private static void outputSchemaFields(FileWriter output_txt_doc, SchemaFieldArray field_array) throws IOException, PDFException {
        if (field_array.getSize() <= 0) return;
            output_txt_doc.write("==== Schema Fields ====\r\n");

        for (int i = 0; i < field_array.getSize(); i++) {
            output_txt_doc.write(String.format("Field index:%d\r\n", i));
            SchemaField field = field_array.getAt(i);
            if (true == field.isEmpty()) continue;
            String key_name = field.getKeyName();
            output_txt_doc.write(String.format("Key name: %s\r\n", key_name));

            String subtype_name = field.getSubtypeName();
            output_txt_doc.write(String.format("Subtype name: %s\r\n", subtype_name));

            String display_name = field.getDisplayName();
            output_txt_doc.write(String.format("Display name: %s\r\n", display_name));

            boolean is_visible = field.isVisible();
            output_txt_doc.write(String.format("Visibility: %s\r\n", is_visible ? "true" : "false"));

            output_txt_doc.write("========\r\n");
        }
    }

    private static void outputPortfolioProperties(FileWriter output_txt_doc, Portfolio portfolio) throws IOException, PDFException {
        output_txt_doc.write("==== Portfolio Properties ====\r\n");
        String initial_filespec_keyname = portfolio.getInitialFileSpecKeyName();
        output_txt_doc.write(String.format("Initial FileSpec Key Name:%s\r\n", initial_filespec_keyname));

        int view_mode = portfolio.getInitialViewMode();
        String view_mode_str = "";
        switch (view_mode) {
            case Portfolio.e_InitialViewUnknownMode:
                view_mode_str = "Unknown";
                break;
            case Portfolio.e_InitialViewDetailMode:
                view_mode_str = "Detail";
                break;
            case Portfolio.e_InitialViewTileMode:
                view_mode_str = "Tile";
                break;
            case Portfolio.e_InitialViewHidden:
                view_mode_str = "Hidden";
                break;
        }
        output_txt_doc.write(String.format("Initial View Mode:%s\r\n", view_mode_str));


        boolean is_ascending = portfolio.isSortedInAscending();
        output_txt_doc.write(String.format("Sorting Order:%s\r\n", is_ascending? "Ascending" : "Descending" ));

        String sorting_field_name = portfolio.getSortingFieldKeyName();
        output_txt_doc.write(String.format("Sorting Field Key Name:%s\r\n", sorting_field_name));

        SchemaFieldArray field_array = portfolio.getSchemaFields();
        outputSchemaFields(output_txt_doc, field_array);
    }
    
    private static void outputPortfolioPDFInfo(String portfolio_file_path, FileWriter output_txt_doc) throws IOException, PDFException {
        PDFDoc pdf_doc = new PDFDoc(portfolio_file_path);
        int error_code = pdf_doc.load(null);
        if (error_code != Constants.e_ErrSuccess) {
            System.out.println(String.format("[FAILED] Fail to load Portfolio PDF file %s. Error: %d\n", portfolio_file_path, error_code));
            return;
        }

        if (false == pdf_doc.isPortfolio()) {
            System.out.println(String.format("[FAILED] Fail to output portfolio information for PDF file %s, because it is not a portfolio PDF file.\r\n", portfolio_file_path));
            return;
        }

        Portfolio exist_portfolio = Portfolio.createPortfolio(pdf_doc);
        if (true == exist_portfolio.isEmpty()) {
            System.out.println("[FAILED] Fail to create a portfolio object based an existed portfolio PDF document.\r\n");
            return;
        }

        // Output portfolio properties.
        outputPortfolioProperties(output_txt_doc, exist_portfolio);
        output_txt_doc.write("======================================================================\r\n");

        // Output all nodes.
        output_txt_doc.write("==== Nodes Information ====\r\n");
        PortfolioNode root_node = exist_portfolio.getRootNode();
        PortfolioFolderNode root_folder = new PortfolioFolderNode(root_node);
        PortfolioNodeArray sub_nodes = root_folder.getSortedSubNodes();
        outputSubNodesInfo(output_txt_doc, sub_nodes, 0);
    }

    public static void main(String[] args) throws PDFException {
        createResultFolder(output_path);
        // Initialize library
        int error_code = Library.initialize(sn, key);
        if (error_code != Constants.e_ErrSuccess) {
            System.out.println("Library Initialize Error: " + error_code);
            return;
        }

        try {
            String saved_portfolio_pdf_path = output_path + "new_portfolio.pdf";
            // Create a new portfolio PDF file
            if (creatPortfolioPDF(saved_portfolio_pdf_path)) {
                String output_info_file_path = output_path + "new_portfolio_info.txt";
                FileWriter text_doc= new FileWriter(output_info_file_path, false);
                // Show information of the new portfolio PDF file.
                outputPortfolioPDFInfo(saved_portfolio_pdf_path, text_doc);
                text_doc.close();
            }

            System.out.println("END: Portfolio demo.");
        } catch (Exception e) {
            e.printStackTrace();
        }
        Library.release();
    }
}
