package com.pdflib.cookbook.pcos.special;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

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

/** 
 * Test for the existence of an embedded Distiller profile.
 * If one is found, its contents are retrieved.
 * <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: distiller_profile.java,v 1.5 2007/09/21 11:02:42 stm Exp $
 */
public class distiller_profile extends pcos_cookbook_example {

    /* This is where the data files are. Adjust as necessary. */
    private final static String SEARCH_PATH = "../input";
    
    /* Suffix for recognizing Acrobat Distiller profiles */ 
    private final static String DISTILLER_SUFFIX = ".joboptions";

    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 embedded_file_count = (int) p.get_number(doc, "length:names/EmbeddedFiles");
        
        int profile_count = 0;
        for (int i = 0; i < embedded_file_count; i += 1) {
            if (get_profile(p, doc, filename, i)) {
                profile_count += 1;
            }
        }
        
        if (profile_count == 0) {
            System.out.println("Distiller profile not found");
        }
   
        p.close_document(doc);
    }

    /**
     * Examines an embedded file whether it is a distiller profile, and if
     * applicable extracts it.
     * 
     * @param p pCOS object
     * @param doc pCOS document handle
     * @param filename input filename
     * @param embedded_file_number number of embedded file to look at
     * @return true if Distiller profile was found
     * 
     * @throws pCOSException
     * @throws Exception
     */
    private boolean get_profile(pCOS p, int doc, String filename,
            int embedded_file_number)
        throws pCOSException, Exception {
        
        boolean retval = false;
        
        final String key = "names/EmbeddedFiles[" + embedded_file_number + "]";
        
        /*
         * Look at the /F entry for the filename suffix, in order to determine
         * whether we have a distiller profile.
         */
        final String file_specification = p.get_string(doc, key + "/F");
        
        String suffix = "";
        if (file_specification.length() >= DISTILLER_SUFFIX.length()) {
            suffix = file_specification.substring(file_specification.length() -
                DISTILLER_SUFFIX.length());
        }
        
        if (suffix.compareToIgnoreCase(DISTILLER_SUFFIX) == 0) {        
            final String objtype = p.get_string(doc, "type:" + key + "/EF/F");
            if (objtype.equals("stream")) {
                byte[] contents = p.get_stream(doc, "", key + "/EF/F");
                if (contents != null && contents.length > 0) {
                    write_profile(filename, contents);
                    retval = true;
                }
                else {
                    System.out.println("Distiller profile not found");
                }
            }
            else {
                System.out.println("Distiller profile not found");
            }
        }
        
        return retval;
    }

    /**
     * Writes the profile to a file with a unique name.
     * 
     * @param contents the contents of the distiller profile
     * 
     * @throws Exception unexpected suffix of input file name
     */
    private void write_profile(String filename, byte[] contents) throws Exception {
        File original_path = new File(filename);
        String base_name = original_path.getName();
        
        /*
         * Strip off the ".pdf" part of the file name
         */
        String suffix = "";
        if (base_name.length() >= 4) {
            suffix = base_name.substring(base_name.length() - 4);
        }
        
        if (suffix.compareToIgnoreCase(".pdf") != 0) {
            throw new Exception("Input document has unexpected suffix \""
                + suffix + "\" (expected \".pdf\")");
        }
        
        base_name = base_name.substring(0, base_name.length() - 4);

        try {
            /*
             * create a new unique file in the current directory and write the
             * contents of the profile to it
             */
            File distiller_file =
                File.createTempFile(base_name + "_", ".joboptions",
                                    new File("."));

            FileOutputStream distiller_stream =
                        new FileOutputStream(distiller_file);
            distiller_stream.write(contents);
            distiller_stream.close();
            
            System.out.println("Distiller profile extracted to file \""
                + distiller_file.getName() + "\"");
        }
        catch (IOException e) {
            System.err.println("IOException occured:");
            e.printStackTrace();
        }
    }
    
    public distiller_profile(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[]) {
        distiller_profile example = new distiller_profile(argv,
            "Distiller profile", SEARCH_PATH,
            "$RCSfile: distiller_profile.java,v $", "$Revision: 1.5 $");
        example.execute();
    }
}
