package com.test;

import static com.test.PDFConstants.PRINTLIST_NO;

import java.awt.Color;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.sql.SQLException;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.ExceptionConverter;
import com.lowagie.text.Font;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.ColumnText;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfPageEventHelper;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;

/**
 * @author sarganesan
 * 
 */
public class PrintListPDFGenerator {

	private static final SimpleDateFormat SDF = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm");
	public static final String RESULT = "header_footer_5.pdf";

	/**
	 * @param shipmentDetail
	 * @return
	 * @throws SQLException
	 * @throws DocumentException
	 * @throws IOException
	 */
	public ByteArrayOutputStream createPdf(List<ShipmentDetail> shipmentDetail)
			throws DocumentException, IOException {

		ByteArrayOutputStream bout = new ByteArrayOutputStream();

		Document document = new Document(PageSize.A4.rotate());
		document.setMargins(30, 30, 30, 30);
		PdfWriter writer = PdfWriter.getInstance(document,
				new FileOutputStream(RESULT));
		TableHeader event = new TableHeader();
		writer.setPageEvent(event);

		// PdfWriter.getInstance(document, bout);
		try {
			document.open();
			Font font = new Font(Font.HELVETICA, 10, Font.BOLD);

			Paragraph listHeading = new Paragraph(
					"Bulk Posting OF REGISTERED ARTICLES", font);
			listHeading.setAlignment(1);

			document.add(listHeading);

			document.add(getTable(populateShipment()));

			// document.add(getTable(shipmentDetail));

			document.close();
		} catch (DocumentException de) {
			// CommonHelper.log(PrintListPDFGenerator.class, LogLevel.ERROR,
			// "pdf creation failed", de);
		}

		return bout;

	}

	/**
	 * @param ShipmentDetail
	 * @return
	 * @throws SQLException
	 * @throws DocumentException
	 * @throws IOException
	 */
	public PdfPTable getTable(List<ShipmentDetail> ShipmentDetail)
			throws DocumentException, IOException {
		// Create a table with 9 columns
		PdfPTable table = new PdfPTable(new float[] { 1, 2.35f, 3.5f, 3.5f, 1.5f, 2, 2,
				1.5f, 2 });
		table.setWidthPercentage(100f);
		table.getDefaultCell().setUseAscender(true);
		table.getDefaultCell().setUseDescender(true);
		// Add the first header row
		Font font = new Font();
		// f.setColor(BaseColor.WHITE);
		font.setSize(8);
		PdfPCell headerNo = new PdfPCell(new Phrase(PRINTLIST_NO, font));

		

		// table.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY);

		headerNo = new PdfPCell(new Phrase(PRINTLIST_NO, font));
		headerNo.setHorizontalAlignment(Element.ALIGN_CENTER);
		table.addCell(headerNo);

		PdfPCell headerTrackNo = new PdfPCell(new Phrase("ADDRESSEE NAME",
				font));
		headerTrackNo.setHorizontalAlignment(Element.ALIGN_CENTER);
		table.addCell(headerTrackNo);

		PdfPCell headerSentFrom = new PdfPCell(new Phrase("ADDRESS 1",
				font));
		headerSentFrom.setHorizontalAlignment(Element.ALIGN_CENTER);
		table.addCell(headerSentFrom);

		PdfPCell headerDescription = new PdfPCell(new Phrase(
				"ADDRESS 2", font));
		headerDescription.setHorizontalAlignment(Element.ALIGN_CENTER);
		table.addCell(headerDescription);

		PdfPCell headerQty = new PdfPCell(new Phrase("POST CODE", font));
		headerQty.setHorizontalAlignment(Element.ALIGN_CENTER);
		table.addCell(headerQty);

		PdfPCell headerWeight = new PdfPCell(new Phrase("COUNTRY", font));
		headerWeight.setHorizontalAlignment(Element.ALIGN_CENTER);
		table.addCell(headerWeight);

		PdfPCell headerOrigin = new PdfPCell(new Phrase("RR NO.", font));
		headerOrigin.setHorizontalAlignment(Element.ALIGN_CENTER);
		table.addCell(headerOrigin);

		PdfPCell commonValue = new PdfPCell(new Phrase("WEIGHT PER ARTICLE (gm)", font));

		// PdfPCell headerValue = new PdfPCell(new Phrase(PRINTLIST_VALUE,
		// font));
		commonValue.setHorizontalAlignment(Element.ALIGN_CENTER);
		table.addCell(commonValue);

		// PdfPCell headerShippingFees = new PdfPCell(new Phrase(
		// PRINTLIST_SHIPPING_FEES, font));

		commonValue.setPhrase(new Phrase("REMARKS", font));
		commonValue.setHorizontalAlignment(Element.ALIGN_CENTER);
		table.addCell(commonValue);
		

		
		
		
		
		
		headerNo = new PdfPCell(getFooterTable());
		headerNo.setColspan(9);
		headerNo.setPadding(0);
		//PdfPTable footTable= getFooterTable();
	 
		/*footTable.setSpacingAfter(0);
		footTable.setSpacingBefore(0);
		headerNo.addElement(footTable);*/
		
		table.addCell(headerNo);

		table.getDefaultCell().setBackgroundColor(null);
		table.setHeaderRows(2);
		table.setFooterRows(1);
		
		
	

		
		table.setSplitLate(true);
		// table.setSplitRows(false);
		font.setSize(8);

		int listCount = 1;
		for (ShipmentDetail shipment : ShipmentDetail) {

			PdfPCell noCell = new PdfPCell(new Phrase(String
					.valueOf(listCount++), font));

			noCell.setHorizontalAlignment(Element.ALIGN_CENTER);
			table.addCell(noCell);

			PdfPCell trackingNo = new PdfPCell(new Phrase(shipment
					.getTrackingNumber(), font));

			table.addCell(trackingNo);

			PdfPCell fromAddress = new PdfPCell((new Phrase(
					toAddressString(shipment.getFromAddress()), font)));

			table.addCell(fromAddress);

			PdfPTable descTable = new PdfPTable(1);
			PdfPTable qtyTable = new PdfPTable(1);
			PdfPTable weightTable = new PdfPTable(1);
			PdfPTable originTable = new PdfPTable(1);
			PdfPTable valueTable = new PdfPTable(1);

			descTable.setHeaderRows(0);
			qtyTable.setHeaderRows(0);
			weightTable.setHeaderRows(0);
			originTable.setHeaderRows(0);
			valueTable.setHeaderRows(0);
			descTable.setSpacingAfter(0);
			descTable.setSpacingAfter(0);

			qtyTable.setSpacingAfter(0);
			qtyTable.setSpacingAfter(0);
			weightTable.setSpacingAfter(0);
			weightTable.setSpacingAfter(0);
			originTable.setSpacingAfter(0);
			originTable.setSpacingAfter(0);
			valueTable.setSpacingAfter(0);
			valueTable.setSpacingAfter(0);
			String itemDescription = new String();
			for (ItemDetail item : shipment.getItemDetails()) {

				itemDescription = item.getCustomsDescription();
				PdfPCell descCell = new PdfPCell(new Phrase(itemDescription,
						font));
				if (itemDescription == null || itemDescription.equals("")) {
					itemDescription = "           ";

				}

				descTable.addCell(new PdfPCell(
						new Phrase(itemDescription, font)));

				qtyTable.addCell(new PdfPCell(new Phrase(String.valueOf(item
						.getOrderQuantity()), font)));
				weightTable.addCell(new PdfPCell(new Phrase(String.valueOf(item
						.getCustomsWeight()), font)));
				// TODO once origin is populated in itemtable , we needto modify
				// addedshipping details
				originTable.addCell(new PdfPCell(new Phrase("China", font)));

				valueTable.addCell(new PdfPCell(new Phrase(
						NumberFormat.getCurrencyInstance(Locale.US).format(
								item.getPrice()), font)));

			}

			PdfPCell descriptionCell = new PdfPCell(descTable);
			descriptionCell.setPadding(0);
			table.addCell(descriptionCell);

			PdfPCell qtyCell = new PdfPCell(qtyTable);
			descriptionCell.setPadding(0);
			table.addCell(qtyCell);

			PdfPCell weightCell = new PdfPCell(weightTable);
			descriptionCell.setPadding(0);
			table.addCell(weightCell);

			PdfPCell originCell = new PdfPCell(originTable);
			descriptionCell.setPadding(0);
			table.addCell(originCell);

			PdfPCell valueCell = new PdfPCell(valueTable);
			descriptionCell.setPadding(0);
			table.addCell(valueCell);

			PdfPCell shippingFees = new PdfPCell((new Phrase(NumberFormat
					.getCurrencyInstance(Locale.US).format(
							shipment.getShippingCost()), font)));
			shippingFees.setVerticalAlignment(Element.ALIGN_MIDDLE);
			table.addCell(shippingFees);

			/*
			 * PdfPCell toAddress = new PdfPCell((new Phrase(
			 * toAddressString(shipment.getFromAddress()), font)));
			 * 
			 * table.addCell(toAddress);
			 */

		}

		return table;
	}

	public List<ShipmentDetail> populateShipment() {
		List<ShipmentDetail> shipments = new ArrayList<ShipmentDetail>();

		for (int j = 0; j < 100; j++) {

			ShipmentDetail shipment = new ShipmentDetail();
			shipment.setTrackingNumber("LK00221555TH");

			AddressDetail address = new AddressDetail();
			address.setAddressLine1("4/F No:223, EAST Yanan Rd ");
			address.setAddressLine2("SHANGAI");
			address.setState("State");
			address.setCity("CHINA");
			address.setZipCode("200001");
			//address.setPhone("044229328392");
			shipment.setFromAddress(address);
			shipment.setToAddress(address);
			shipment.setShippingCost(10.00);
			List<ItemDetail> items = new ArrayList<ItemDetail>();

			for (int i = 0; i <1; i++) {
				ItemDetail item = new ItemDetail();
				item.setCustomsDescription("3 items");
				item.setOrderQuantity(2);
				item.setCustomsWeight(200.29);
				item.setCustomsValue(4500.00);
				item.setItemTitle("China");
				items.add(item);
			}
			shipment.getItemDetails().addAll(items);
			shipments.add(shipment);
		}

		return shipments;
	}

	public String toAddressString(AddressDetail addressDetail) {

		StringWriter address = new StringWriter();
		address.append(addressDetail.getAddressLine1()).append(
				System.getProperty("line.separator"));
		if (addressDetail.getAddressLine2() != null
				&& !addressDetail.getAddressLine2().equals(""))
			address.append(addressDetail.getAddressLine2()).append(
					System.getProperty("line.separator"));

		address.append(addressDetail.getCity()).append(
				System.getProperty("line.separator")).append(
				addressDetail.getState()).append(addressDetail.getZipCode());
		return address.toString();

	}

	public static void main(String[] args) throws SQLException,
			DocumentException, IOException {
		new PrintListPDFGenerator().createPdf(null);
	}

	class TableHeader extends PdfPageEventHelper {
		/** The header text. */
		String header;
		/** The template with the total number of pages. */
		PdfTemplate total;

		/**
		 * Allows us to change the content of the header.
		 * 
		 * @param header
		 *            The new header String
		 */
		public void setHeader(String header) {
			this.header = header;
		}

		/**
		 * Creates the PdfTemplate that will hold the total number of pages.
		 * 
		 * @see com.itextpdf.text.pdf.PdfPageEventHelper#onOpenDocument(com.itextpdf.text.pdf.PdfWriter,
		 *      com.itextpdf.text.Document)
		 */
		public void onOpenDocument(PdfWriter writer, Document document) {
			total = writer.getDirectContent().createTemplate(30, 16);
		}

		/**
		 * Adds a header to every page
		 * 
		 * @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(com.itextpdf.text.pdf.PdfWriter,
		 *      com.itextpdf.text.Document)
		 */
		public void onEndPage(PdfWriter writer, Document document) {
			PdfPTable table = new PdfPTable(3);
			try {
				table.setWidths(new int[] { 24, 24, 2 });
				table.setTotalWidth(527);
				table.setLockedWidth(true);
				table.getDefaultCell().setFixedHeight(20);
				table.getDefaultCell().setBorder(Rectangle.BOTTOM);
				table.addCell(header);
				table.getDefaultCell().setHorizontalAlignment(
						Element.ALIGN_RIGHT);
				table.addCell(String.format("Page %d of", writer
						.getPageNumber()));
				PdfPCell cell = new PdfPCell(Image.getInstance(total));
				cell.setBorder(Rectangle.BOTTOM);
				table.addCell(cell);
				table.writeSelectedRows(0, -1, 34, 803, writer
						.getDirectContent());
			} catch (DocumentException de) {
				throw new ExceptionConverter(de);
			}
		}

		/**
		 * Fills out the total number of pages before the document is closed.
		 * 
		 * @see com.itextpdf.text.pdf.PdfPageEventHelper#onCloseDocument(com.itextpdf.text.pdf.PdfWriter,
		 *      com.itextpdf.text.Document)
		 */
		public void onCloseDocument(PdfWriter writer, Document document) {
			ColumnText.showTextAligned(total, Element.ALIGN_LEFT, new Phrase(
					String.valueOf(writer.getPageNumber() - 1)), 2, 2, 0);
		}
	}
	
	
	public PdfPTable getFooterTable()
	{
		PdfPTable footTab= new PdfPTable(new float[] { 1, 2.35f, 3.5f, 3.5f, 1.5f, 2, 2,
				1.5f, 2 });
		PdfPCell span4Cell= new PdfPCell(new Phrase(""));
		span4Cell.setColspan(4);
		span4Cell.setBackgroundColor(Color.DARK_GRAY);
		
		footTab.addCell(span4Cell);
		
		PdfPCell span2Cell= new PdfPCell(new Phrase("Total Quantity"));
		span2Cell.setColspan(2);
		footTab.addCell(span2Cell);
		
		footTab.addCell(new PdfPCell(new Phrase("")));
		
		span2Cell= new PdfPCell(new Phrase(""));
		span2Cell.setColspan(2);
		span2Cell.setBackgroundColor(Color.DARK_GRAY);
		footTab.addCell(span2Cell);
		
		
		
		
		PdfPTable footTab1= new PdfPTable(1);
		span2Cell= new PdfPCell(new Phrase("PPI PERMIT HOLDERS NAME AND ADDRESS"+"\n"+"NAME:"+"\n"+"\n"+"ADDRESS"+"\n"+"   "));
		footTab1.addCell(span2Cell);
		
		
		PdfPTable footTab2= new PdfPTable(2);
		footTab2.addCell(new PdfPCell(new Phrase("Contact No")));
		footTab2.addCell(new PdfPCell(new Phrase("FAX No")));
		span2Cell= new PdfPCell(footTab2);
		footTab1.addCell(span2Cell);
		
				
		
		PdfPCell secondRow= new PdfPCell(footTab1);
		secondRow.setColspan(3);
		footTab.addCell(secondRow);
		
		
		
		PdfPTable footTab3= new PdfPTable(1);
		footTab3.addCell(new PdfPCell(new Phrase("PPI PERMIT NO:"+"\n"+""+"\n")));
		footTab3.addCell(new PdfPCell(new Phrase("SIGNATURE/DATE")));
		
		PdfPCell secondRow1_2= new PdfPCell(footTab3);
		
		footTab.addCell(secondRow1_2);
		
		
		PdfPCell secondRow1_3= new PdfPCell(new Phrase("TRANSMISSION MODE"));
		secondRow1_3.setColspan(2);
		footTab.addCell(secondRow1_3);
		
		
		PdfPCell secondRow1= new PdfPCell(new Phrase("ACCEPTED BY :(SINGAPORE POST LIMITED)"+"\n"+"\n"+"SIGNATURE/DATE"));
		secondRow1.setColspan(3);
		footTab.addCell(secondRow1);
		
		return footTab;
		
	}

}
