package com.ejie.aa21b.pdf;

import java.io.IOException;
import java.net.MalformedURLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;

import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.ExceptionConverter;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;

/**
 * En esta clase englobamos aquellas variables y funciones comunes en los
 * informes que sacamos con itext
 * 
 *  
 * 
 */
public class PdfBuilder {
	private static final Logger logger = LoggerFactory
			.getLogger(PdfBuilder.class);
	public ReloadableResourceBundleMessageSource appMessageSource;
	public Locale locale;
	PdfContentByte cb;

	public PdfBuilder(ReloadableResourceBundleMessageSource appMessageSource,
			Locale locale) {
		super();
		this.appMessageSource = appMessageSource;
		this.locale = locale;
	}

	/**
	 * Esta clase interna escribe la cabecera del codumento
	 * 
	 *  
	 * 
	 */
	class TableHeader extends PdfPageEventHelper {

		/** The template with the total number of pages. */
		PdfTemplate total;
		Image logo;

		/**
		 * 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);
			cb = writer.getDirectContent();
			try {
				logo = Image
						.getInstance("/datos/aa21b/file/gobierno_vasco.png");
			} catch (BadElementException e) {
				// TODO Auto-generated catch block
				logger.error(e.getMessage());
				StackTraceElement[] els = e.getStackTrace();
				for (StackTraceElement el : els) {
					logger.error(el.toString());
				}
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				logger.error(e.getMessage());
				StackTraceElement[] els = e.getStackTrace();
				for (StackTraceElement el : els) {
					logger.error(el.toString());
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				logger.error(e.getMessage());
				StackTraceElement[] els = e.getStackTrace();
				for (StackTraceElement el : els) {
					logger.error(el.toString());
				}
			}
		}

		/**
		 * 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 doc) {
			try {

				PdfPTable headerTbl = new PdfPTable(3);
				headerTbl.setWidths(new float[] { 1, 4, 1 });
				headerTbl.setTotalWidth(doc.getPageSize().getWidth());
				// headerTbl.setHorizontalAlignment(Element.ALIGN_CENTER);
				Font elve = new Font(Font.FontFamily.HELVETICA, 8);
				// Fecha

				DateFormat dateFormat;
				if (locale.getLanguage().equals("es"))
					dateFormat = new SimpleDateFormat("dd-MM-yyyy"); //$NON-NLS-1$
				else
					dateFormat = new SimpleDateFormat("yyyy-MM-dd");
				Date n = new Date();
				PdfPCell cell1 = new PdfPCell(new Paragraph(
						dateFormat.format(n), //$NON-NLS-1$
						elve));
				cell1.setBorder(Rectangle.NO_BORDER);
				cell1.setPaddingLeft(50);
				cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);
				headerTbl.addCell(cell1);
				// Número páginas

				//$NON-NLS-1$
				logo.scalePercent(40);
				PdfPCell cell = new PdfPCell(logo);
				cell.setHorizontalAlignment(Element.ALIGN_CENTER);
				cell.setVerticalAlignment(Element.ALIGN_TOP);
				cell.setPadding(0);
				// cell.setPaddingRight(20);
				cell.setBorder(Rectangle.NO_BORDER);
				// cell.setColspan(2);
				headerTbl.addCell(cell);
				String texto = "";

				texto = appMessageSource.getMessage("paginade", null,
						LocaleContextHolder.getLocale());

				PdfPCell cell3 = new PdfPCell(new Paragraph(String.format(
						texto, writer.getPageNumber()), //$NON-NLS-1$
						elve));
				cell3.setPaddingRight(50);
				cell3.setBorder(Rectangle.NO_BORDER);
				cell3.setHorizontalAlignment(Element.ALIGN_RIGHT);
				cell3.setVerticalAlignment(Element.ALIGN_MIDDLE);

				headerTbl.addCell(cell3);

				headerTbl.writeSelectedRows(0, -1, 0, (doc.getPageSize()
						.getHeight() - 10), writer.getDirectContent());

				cb.saveState();
				// System.out.println(doc.top());
				cb.addTemplate(total, doc.right() - 77, doc.top() + 41);
				cb.restoreState();

			} catch (Exception 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) {
			// Font elve = new Font(Font.FontFamily.HELVETICA, 8);
			total.beginText();
			try {
				total.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA,
						BaseFont.WINANSI, BaseFont.NOT_EMBEDDED), 8);
			} catch (DocumentException e) {
				// TODO Auto-generated catch block
				logger.error(e.getMessage());
				StackTraceElement[] els = e.getStackTrace();
				for (StackTraceElement el : els) {
					logger.error(el.toString());
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				logger.error(e.getMessage());
				StackTraceElement[] els = e.getStackTrace();
				for (StackTraceElement el : els) {
					logger.error(el.toString());
				}
			}
			total.setTextMatrix(0, 0);
			total.showText((writer.getPageNumber() - 1) + "");
			total.endText();
		}
	}

}
