package org.cmdline.sudoku;

import java.io.*;
import java.net.URL;
import com.lowagie.text.*;
import com.lowagie.text.pdf.PdfWriter;
import java.awt.Color;
import java.awt.image.BufferedImage;

public class Puzzle2PDF {

	private Document document = new Document(PageSize.A4, 50, 50, 50, 50);
	
	public Puzzle2PDF(String puzzlePath,String pdfPath,String header,String description,String notes) {
		try {
			if (pdfPath == null)
				PdfWriter.getInstance(document,new FileOutputStream("pdfout.pdf"));
			else 
				PdfWriter.getInstance(document,new FileOutputStream(pdfPath));
			document.addAuthor("Sunday Sudoku Solver");
			document.addSubject("PDF puzzle export");

			// we define some fonts
			Font chapterFont = new Font(Font.HELVETICA, 24, Font.NORMAL, new Color(255, 0, 0));
			Font sectionFont = new Font(Font.HELVETICA,16,Font.BOLD,new Color(0,0,0));
			Paragraph title = new Paragraph(header,chapterFont);
			title.setAlignment(Element.ALIGN_CENTER);
		
			// we define a header and a footer
			HeaderFooter hdr = new HeaderFooter(new Phrase("Sunday Sudoku Solver"),false);

			// We open the document for writing
			document.open();
			document.setHeader(hdr);
			document.add(title);
			if (description != null && !description.equals("")) {
				document.add(new Paragraph("Description:",sectionFont));
				document.add(new Paragraph(16,new Chunk(description)));
			}
			if (notes != null && !notes.equals("")) {
				document.add(new Paragraph("Notes:",sectionFont));
				document.add(new Paragraph(16,new Chunk(notes)));
			}
			// For spacing - (Should be some way to do leading/trailing I think, would be better)
			document.add(new Paragraph(18,new Chunk("")));
			Image img = null;
			if (System.getProperty("os.name").startsWith("Windows"))
				img = new Jpeg(getImageURL(new StringBuffer("/").append(puzzlePath).toString()));
			else img = new Jpeg(getImageURL(puzzlePath));
			img.setAlignment(Image.MIDDLE + Image.UNDERLYING);
			document.add(img);
			// we close the document
			document.close();
		}
		catch (Exception ex) { ex.printStackTrace(); }
	}
	
	private URL getImageURL(String path) {
		try {
			return new URL(new StringBuffer("file://localhost").append(path).toString()); 
		}
		catch (java.net.MalformedURLException mue) { mue.printStackTrace(); }
		return null;
	}
}