package com.invantive.util;

import java.awt.HeadlessException;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.util.List;
import javax.imageio.ImageIO;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.util.PDFImageWriter;

/**
 * Convert a PDF document to an image.
 */
public class Pdf2ImageApp
{
  public static void main(String[] args) 
  throws Exception
  {
    String password = "";
    String pdfFile = null;
    String outputPrefix = "";
    String imageFormat = "png";
    int startPage = 1;
    int endPage = Integer.MAX_VALUE;
    String color = "rgb";
    int resolution = 300;
    float compressionQuality = 0.0f;
    //
    for (int i = 0; i < args.length; i++)
    {
      if (args[i].equals("-password") )
      {
        i++;
        if (i >= args.length)
        {
          usage();
        }
        password = args[i];
      }
      else if (args[i].equals("-startPage"))
      {
        i++;
        if (i >= args.length)
        {
          usage();
        }
        startPage = Integer.parseInt(args[i]);
      }
      else if (args[i].equals("-endPage") )
      {
        i++;
        if (i >= args.length)
        {
          usage();
        }
        endPage = Integer.parseInt(args[i]);
      }
      else if (args[i].equals("-imageType"))
      {
        i++;
        imageFormat = args[i];
      }
      else if (args[i].equals("-outputPrefix"))
      {
        i++;
        outputPrefix = args[i];
      }
      else if (args[i].equals("-color"))
      {
        i++;
        color = args[i];
      }
      else if (args[i].equals("-resolution"))
      {
        i++;
        resolution = Integer.parseInt(args[i]);
      }
      else if (args[i].equals("-quality"))
      {
        i++;
        compressionQuality = Float.parseFloat(args[i]);
      }
      else
      {
        if (pdfFile == null)
        {
          pdfFile = args[i];
        }
        else
        {
          System.err.println("Multiple PDF files not supported.");
          usage();
        }
      }
    }
    //
    int imageType = 24;
    if ("bilevel".equalsIgnoreCase(color))
    {
      imageType = BufferedImage.TYPE_BYTE_BINARY;
    }
    else if ("indexed".equalsIgnoreCase(color))
    {
      imageType = BufferedImage.TYPE_BYTE_INDEXED;
    }
    else if ("gray".equalsIgnoreCase(color))
    {
      imageType = BufferedImage.TYPE_BYTE_GRAY;
    }
    else if ("rgb".equalsIgnoreCase(color))
    {
      imageType = BufferedImage.TYPE_INT_RGB;
    }
    else if ("rgba".equalsIgnoreCase(color))
    {
      imageType = BufferedImage.TYPE_INT_ARGB;
    }
    else
    {
      System.err.println( "Invalid color " + color + " chosen." );
      usage();
    }
    //
    if (pdfFile == null)
    {
      System.err.println("No PDF file provided.");
      usage();
    }
    else
    {
      Pdf2Image p2i = new Pdf2Image();
      p2i.setPassword(password);
      p2i.setImageFormat(imageFormat);
      p2i.setImageType(imageType);
      p2i.setStartPage(startPage);
      p2i.setEndPage(endPage);
      p2i.setResolution(resolution);
      p2i.setCompressionQuality(compressionQuality);
      p2i.savePdfFileAsImage(pdfFile, outputPrefix, "%p");
      //System.err.println("Sent " + pdfFile + " to "+ outputPrefix);
    }
  }

  private static void usage()
  {
    System.err.println
    ( "Usage: java com.invantive.util.Pdf2Image [OPTIONS] <PDF file>\n" 
      + "  -password  <password>          Password to decrypt document (default: none)\n"
      + "  -imageType <image type>        (" + getImageFormats() + ")\n"
      + "  -outputPrefix <output prefix>  Filename prefix for image files, %p is replaced by page number (default: none)\n"
      + "  -startPage <number>            The first page to start extraction (default: 1)\n"
      + "  -endPage <number>              The last page to extract(inclusive) (default: last)\n"
      + "  -color <string>                The color depth (valid: bilevel, indexed, gray, rgb, rgba, default: rgb)\n"
      + "  -quality <float>               The compression quality (0..1 with 0 is minimize size and 1 is maximize quality (default: 0)\n"
      + "  -resolution <number>           The bitmap resolution in dpi (default: 300)\n"
      + "  <PDF file>                     The PDF document to use (default: none)\n"
    );
    System.exit(1);
  }
  
  private static String getImageFormats()
  {
    StringBuffer retval = new StringBuffer();
    String[] formats = ImageIO.getReaderFormatNames();
    for (int i = 0; i < formats.length; i++)
    {
      retval.append( formats[i] );
      if ( i + 1 < formats.length)
      {
        retval.append( "," );
      }
    }
    return retval.toString();
  }
}
