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;

/**
 * Extract one or more ICC profiles from the document output intents.
 * <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: icc_profiles.java,v 1.1 2007/09/21 12:58:28 stm Exp $
 */
public class icc_profiles 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 output_intent_count = (int) p.get_number(doc, "length:/Root/OutputIntents");
        
        for (int oi = 0; oi < output_intent_count; oi += 1) {
            System.out.println("Output intent " + (oi + 1));            
            process_output_intent(p, doc, filename, oi);
        }
        
        p.close_document(doc);
    }

    /**
     * Examines the output intent given by parameter oi, and writes out ICC
     * profile if applicable.
     * 
     * @param p
     *            pCOS object
     * @param doc
     *            pCOS document handle
     * @param filename
     *            name of the PDF input document
     * @param oi
     *            index in "/Root/OutputIntents" array
     * 
     * @throws pCOSException
     */
    private void process_output_intent(pCOS p, int doc, String filename, int oi)
            throws pCOSException, Exception {
        /*
         * The pCOS path to the given output intent
         */
        final String oi_key = "/Root/OutputIntents[" + oi + "]";

        print_info(p, doc, oi_key + "/S", "Subtype", "name", true);
        print_info(p, doc, oi_key + "/OutputCondition", "Output Condition", "string", false);
        print_info(p, doc, oi_key + "/OutputConditionIdentifier", "Identifier", "string", true);
        print_info(p, doc, oi_key + "/RegistryName", "Registry", "string", false);
        print_info(p, doc, oi_key + "/Info", "Info", "string", false);
        
        String objtype = p.get_string(doc, "type:" + oi_key + "/DestOutputProfile");
        if (objtype.equals("stream")) {
            byte[] contents = p.get_stream(doc, "", oi_key + "/DestOutputProfile");
            if (contents != null && contents.length > 0) {
                String subtype = p.get_string(doc, oi_key + "/S");
                write_profile(filename, subtype, contents);
            }
            else {
                System.out.println("  No ICC profile found");
            }
        }
        else {
            System.out.println("  No ICC profile found");
        }
    }

    /**
     * Prints out one of the keys in the output intent dictionary.
     * 
     * @param p
     *            pCOS object
     * @param doc
     *            pCOS document handle
     * @param key
     *            key of interest in the output intent dictionary
     * @param label
     *            human-readable lable
     * @param type
     *            expected type of the value in the dictionary
     * @param required
     *            if true the absence of the key causes an exception
     * 
     * @throws pCOSException
     *             a pCOS error occurred
     * @throws Exception
     *             a required key was not found, the PDF document is damaged
     */
    private void print_info(pCOS p, int doc, String key, String label, String type, boolean required)
            throws pCOSException, Exception {
        String objtype = p.get_string(doc, "type:" + key);
        
        System.out.print("  " + label + ": ");
        
        if (objtype.equals(type)) {
            System.out.print("'" + p.get_string(doc, key) + "'");
        }
        else {
            if (required) {
                throw new Exception("Required key '" + key + "' is missing, cannot continue");
            }
            System.out.print("(not found)");
        }
        
        System.out.println();
    }

    /**
     * Writes the ICC profile to a file with a unique name.
     * 
     * @param filename
     *            name of PDF input document
     * @param subtype
     *            output intent subtype from output intent dictionary
     * @param contents
     *            the contents of the distiller profile
     * 
     * @throws Exception
     *             unexpected suffix of input file name
     */
    private void write_profile(String filename, String subtype,
            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 ICC profile to it
             */
            File icc_profile_file = File.createTempFile(base_name + "_"
                    + subtype + "_", ".icc", new File("."));

            FileOutputStream icc_profile_stream = new FileOutputStream(
                    icc_profile_file);
            icc_profile_stream.write(contents);
            icc_profile_stream.close();

            System.out.println("  ICC profile extracted to file \""
                    + icc_profile_file.getName() + "\"");
        }
        catch (IOException e) {
            System.err.println("IOException occured:");
            e.printStackTrace();
        }
    }
    
    public icc_profiles(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[]) {
        icc_profiles example = new icc_profiles(argv, "Output intent ICC profiles",
            SEARCH_PATH, "$RCSfile: icc_profiles.java,v $", "$Revision: 1.1 $");
        example.execute();
    }
}
