package com.industriallogic.shopping.catalogTests;

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

import com.lowagie.text.BadElementException;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;


public class MyNestedTable {
	private static final String SOME_MASSIVE_TEXT= 
	"Yankee doodle went to town, riding on a pony, he stuck a feather " +	"in his cap and called it macaroni. Yankee doodle doodle do, yankee " +	"doodle dandy. All the lads and lassies are as sweet as sugar and candy.";

	private static final String SOME_OTHER_MASSIVE_TEXT= 
	"Jack and Jill went up the hill to fetch a pail of water. Jack fell down" +	" and broke his crown and Jill came tumbling after.";
	    	    
    /** 
     * Creates table for specified no of cols, equidistributing columns
     * @param numCols
     * @return Table
     * @throws BadElementException
     */
	public PdfPTable createPdfPTable(int numCols) throws DocumentException {
		PdfPTable table = new PdfPTable(numCols);
		float [] widths = new float[numCols];
		float width = ((float)100)/numCols;
		for (int i=0;i<numCols;i++) {
			widths[i] = width;
		}
		table.setWidthPercentage(100.0f);
		table.setWidths(widths);
		
		return table;
	}	
    
	public void runExample() {
		System.out.println("Chapter 5 example 14: nested tables");
		Document document = new Document();
		try {
			PdfWriter.getInstance(document, new FileOutputStream("resources/pdf/myNestedPdfPTable.pdf"));
			document.open();
			PdfPTable parentPdfPTable = createPdfPTable(3);    
			addChildPdfPTablesTo(parentPdfPTable);
        	document.add(parentPdfPTable);
		}
		catch(DocumentException de) {
			System.err.println(de.getMessage());
			de.printStackTrace();
		}
		catch(IOException ioe) {
			System.err.println(ioe.getMessage());
		}
		// step 5: we close the document
		document.close();
	}

	public void addChildPdfPTablesTo(PdfPTable parentPdfPTable) throws BadElementException {
		for (int i=0;i<3;i++) {
			PdfPTable childPdfPTable = new PdfPTable(1);
			childPdfPTable.setWidthPercentage(100);
			addCellsTo(childPdfPTable);
			int row = i/3;
			int col = i%3;
			parentPdfPTable.addCell(childPdfPTable);
		}
	}
	
	private void addCellsTo(PdfPTable table) {
		PdfPCell cellWithLeading20 = new PdfPCell(new Phrase(SOME_MASSIVE_TEXT));
		cellWithLeading20.setLeading(20,0);
		PdfPCell cellWithLeading10 = new PdfPCell(new Phrase(SOME_OTHER_MASSIVE_TEXT));
		cellWithLeading10.setLeading(10,0);
		table.addCell(cellWithLeading20);
		// If the line below is uncommented, there is an exception
		table.addCell(cellWithLeading10);
	}
	
	public static void main(String[] args) {
		MyNestedTable myNestedPdfPTable = new MyNestedTable();
		myNestedPdfPTable.runExample();
	}

}
