package com.pdflib.cookbook.pcos.interactive;

import com.pdflib.pCOS;
import com.pdflib.pCOSException;
import com.pdflib.cookbook.pcos.pcos_cookbook_example;

/**
 * Retrieve form fields.
 * <p>
 * Required software: pCOS interface 3 (pCOS 2.x, PDFlib 7.x, TET 2.2,
 * PLOP 3.x)<br>
 * Required data: PDF document
 * 
 * @version $Id: fields.java,v 1.3 2007/09/19 08:45:30 stm Exp $
 */
public class fields extends pcos_cookbook_example {
    
    /* This is where the data files are. Adjust as necessary. */
    private final static String SEARCH_PATH = "../input";

    public void example_code(pCOS p, String filename) throws pCOSException, Exception {
        /* Open the PDF document */
        int doc = p.open_document(filename, "");
        if (doc == -1)
            throw new Exception("Error: " + p.get_errmsg());
        
        System.out.println("File name: " + p.get_string(doc, "filename"));
        
        int fieldcount = (int) p.get_number(doc, "length:fields");
        if (fieldcount == 0) {
            System.out.println("No form fields found\n");
        }
        else {
            System.out.println(fieldcount + " form fields found");

            for (int f = 0; f < fieldcount; f++) {
                System.out.print("field " + f
                        + ": level="
                        + (int) p.get_number(doc, "fields[" + f + "]/level")
                        + " ");

                String res = p.get_string(doc, "fields[" + f + "]/fullname");
                System.out.print("fullname='" + res + "'; ");

                String objtype = p.get_string(doc, "type:fields[" + f + "]/FT");
                if (objtype.equals("name")) {
                    res = p.get_string(doc, "fields[" + f + "]/FT");
                    System.out.println("type=" + res);
                }
                else {
                    System.out.println("non-terminal field without any type");
                }
            }
        }
        
        p.close_document(doc);
    }
    
    public fields(String[] argv, String readable_name,
        String search_path, String full_rcs_file_name, String revision) {
        super(argv, readable_name, search_path, full_rcs_file_name, revision);
    }

    public static void main(String argv[]) {
        fields example = new fields(argv,
            "Form fields", SEARCH_PATH,
            "$RCSfile: fields.java,v $", "$Revision: 1.3 $");
        example.execute();
    }
}
