package com.ejie.aa20b.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.springframework.context.support.ReloadableResourceBundleMessageSource;

import com.ejie.aa20b.classes.Aa20bFecha;
import com.itextpdf.text.BaseColor;
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.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.Font.FontFamily;
import com.itextpdf.text.pdf.ColumnText;
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
 * 
 * @author iaizpurl
 * 
 */
public class PdfBuilder {
	public ReloadableResourceBundleMessageSource appMessageSource;
	public Locale locale;
	public static final String[] CAMPOS = { "fkzona", "fkcliente", "IDDEPAR",
			"IDCOG", "TRAMITA", "idremesa" };

	public static final String[] NOMBRE = { "countzona", "countcliente",
			"countdep", "countcorg", "counttramita", "countremesa" };
	public static final String[] ETIQUETAS = { "InformeNotifLike.2.zona",
			"InformeNotifLike.2.cliente", "InformeNotifLike.2.departamento",
			"InformeNotifLike.2.direccion", "InformeNotifLike.2.tramitador",
			"InformeNotifLike.2.remesa" };

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

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

		/** The template with the total number of pages. */
		PdfTemplate total;
		private String depCastellano;
		private String depEuskera;

		/**
		 * @param depCastellano
		 *            the depCastellano to set
		 */
		public void setDepCastellano(String depCastellano) {
			this.depCastellano = depCastellano;
		}

		/**
		 * @param depEuskera
		 *            the depEuskera to set
		 */
		public void setDepEuskera(String depEuskera) {
			this.depEuskera = depEuskera;
		}

		/**
		 * 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 doc) {
			try {
				PdfPTable headerTbl = new PdfPTable(2);
				headerTbl.setWidths(new float[] { 1, 1 });
				headerTbl.setTotalWidth(300f);
				headerTbl.setHorizontalAlignment(Element.ALIGN_CENTER);
				Image logo = Image
						.getInstance("/datos/aa20b/file/informes/images/ejgv_main.gif"); //$NON-NLS-1$
				logo.scalePercent(50);
				PdfPCell cell = new PdfPCell(logo);
				cell.setHorizontalAlignment(Element.ALIGN_CENTER);
				cell.setPaddingRight(20);
				cell.setBorder(Rectangle.NO_BORDER);
				cell.setColspan(2);
				headerTbl.addCell(cell);

				Font elve = new Font(Font.FontFamily.HELVETICA, 7);

				PdfPCell cell2 = new PdfPCell(new Paragraph(this.depEuskera,
						elve));
				cell2.setBorder(Rectangle.NO_BORDER);
				cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
				headerTbl.addCell(cell2);
				PdfPCell cell3 = new PdfPCell(new Paragraph(this.depCastellano,
						elve));
				cell3.setBorder(Rectangle.NO_BORDER);
				cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
				headerTbl.addCell(cell3);

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

				PdfPTable headerfooter = new PdfPTable(2);
				headerfooter.setTotalWidth(785f);
				DateFormat dateFormat;
				if (locale.getLanguage().equals("es"))
					dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm"); //$NON-NLS-1$
				else
					dateFormat = new SimpleDateFormat("yyyy/MM/dd  HH:mm");
				Date n = new Date();
				PdfPCell cell5 = new PdfPCell(new Paragraph(
						dateFormat.format(n), //$NON-NLS-1$
						elve));
				cell5.setBorder(Rectangle.NO_BORDER);
				cell5.setHorizontalAlignment(Element.ALIGN_LEFT);

				headerfooter.addCell(cell5);
				PdfPCell cell6 = new PdfPCell(new Paragraph(String.format(
						"%d", writer.getPageNumber()), //$NON-NLS-1$
						elve));
				cell6.setBorder(Rectangle.NO_BORDER);
				cell6.setHorizontalAlignment(Element.ALIGN_RIGHT);

				headerfooter.addCell(cell6);

				headerfooter.writeSelectedRows(0, -1, 30, 30,
						writer.getDirectContent());
			} 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) {
			ColumnText.showTextAligned(total, Element.ALIGN_LEFT, new Phrase(
					String.valueOf(writer.getPageNumber() - 1)), 2, 2, 0);
		}
	}

	/**
	 * Compara la las estad�sticas x e y, y crea las estad�sticas que le
	 * corresponeden a x, comparandolo con Y
	 * 
	 * @param doc
	 * @param x
	 * @param y
	 * @return
	 */
	private PdfPTable compararEstadisticas(Map x, Map y, Font fontDatos) {

		Object x1, x2;
		for (int i = 0; i < CAMPOS.length; i++) {
			x1 = x.get(CAMPOS[i]);
			x2 = y.get(CAMPOS[i]);
			if (i != 4) {

				if (((java.math.BigDecimal) x1).intValue() != ((java.math.BigDecimal) x2)
						.intValue())
					return escribirEstadistica(x, i, fontDatos);
			} else {
				if (!((String) x1).equals((String) x2))
					return escribirEstadistica(x, i, fontDatos);
			}

		}

		return null;
	}

	/**
	 * Escribe la estad�stica del elemento, partiendo desde la posici�n i
	 * 
	 * @param doc
	 * @param elemento
	 * @param i
	 * @return
	 */
	private PdfPTable escribirEstadistica(Map elemento, int i, Font fontDatos) {
		PdfPTable table = new PdfPTable(2);
		table.setSpacingAfter(0);
		table.setSpacingBefore(50);
		table.setWidthPercentage(20);
		float[] columnWidths = new float[] { 3f, 1f };
		try {
			table.setWidths(columnWidths);
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		table.setHorizontalAlignment(Element.ALIGN_LEFT);

		PdfPCell cell1;
		for (int j = NOMBRE.length - 1; j >= i; j--) {
			cell1 = new PdfPCell(new Paragraph(appMessageSource.getMessage(
					ETIQUETAS[j], null, locale), fontDatos));
			cell1.setBorder(PdfPCell.NO_BORDER);
			table.addCell(cell1);

			cell1 = new PdfPCell(new Paragraph(String.valueOf(elemento
					.get(NOMBRE[j])), fontDatos));
			cell1.setBorder(PdfPCell.NO_BORDER);
			table.addCell(cell1);
		}
		return table;

	}

	/**
	 * Crea el xml de estad�sticas para elemento i del analisis
	 * 
	 * @param doc
	 * @param i
	 * @return
	 */
	public PdfPTable crearEstadistica(ArrayList<List> analisis, int i,
			Font fontDatos) {

		if (analisis.size() < i) {
			return null;
		} else if (i == analisis.size() - 1) {
			return escribirEstadistica((Map) analisis.get(i), 0, fontDatos);

		} else {
			return compararEstadisticas((Map) analisis.get(i),
					(Map) analisis.get(i + 1), fontDatos);

		}

	}

	/**
	 * Escribe los titulos de las columnas de la tabla
	 * 
	 * @param Font
	 * @param int
	 * @return
	 */
	public PdfPTable cabeceraSemanasPorEdificios(Font fontCabecera, int nAnio) {
		PdfPTable table = new PdfPTable(56);
		table.setSpacingAfter(0);
		table.setSpacingBefore(0);
		table.setWidthPercentage(100);
		float[] columnWidths = new float[] { 4f, 7f, 1f, 1f, 1f, 1f, 1f, 1f,
				1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f,
				1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f,
				1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f };
		try {
			table.setWidths(columnWidths);
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		table.setHorizontalAlignment(Element.ALIGN_LEFT);

		PdfPCell cell1;
		// Añadimos los meses del año
		String[] letrasMeses;
		try {
			letrasMeses = Aa20bFecha.letraMesSemana(nAnio);
		} catch (Exception e) {
			letrasMeses = null;
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		cell1 = new PdfPCell(new Paragraph("--", fontCabecera));
		cell1.setBackgroundColor(BaseColor.LIGHT_GRAY);
		table.addCell(cell1);
		cell1 = new PdfPCell(new Paragraph("--", fontCabecera));
		cell1.setBackgroundColor(BaseColor.LIGHT_GRAY);
		table.addCell(cell1);

		for (int a = 0; a < 54; a++) {
			cell1 = new PdfPCell(new Paragraph(letrasMeses[a] + "",
					fontCabecera));
			// cell1.setBorder(PdfPCell.NO_BORDER);
			cell1.setBackgroundColor(BaseColor.LIGHT_GRAY);
			table.addCell(cell1);
		}

		// Añadimos las semanas del año
		cell1 = new PdfPCell(new Paragraph(this.appMessageSource.getMessage(
				"prevAnual.codigo", null, locale), fontCabecera));
		// cell1.setBorder(PdfPCell.NO_BORDER);
		cell1.setBackgroundColor(BaseColor.LIGHT_GRAY);
		table.addCell(cell1);
		cell1 = new PdfPCell(new Paragraph(this.appMessageSource.getMessage(
				"prevAnual.equipo", null, locale), fontCabecera));
		cell1.setBackgroundColor(BaseColor.LIGHT_GRAY);
		// cell1.setBorder(PdfPCell.NO_BORDER);
		table.addCell(cell1);
		cell1.setBackgroundColor(BaseColor.LIGHT_GRAY);
		for (int a = 0; a < 54; a++) {
			cell1 = new PdfPCell(new Paragraph(a + "", fontCabecera));
			// cell1.setBorder(PdfPCell.NO_BORDER);
			cell1.setBackgroundColor(BaseColor.LIGHT_GRAY);
			table.addCell(cell1);
		}
		return table;

	}

	/**
	 * Escribe las agrupaciones de la tabla
	 * 
	 * @param Font
	 * @param String
	 * @param String
	 * @param String
	 * @param String
	 * @return
	 */
	public PdfPTable EncabezadoTablaPorEdificios(Font fontCabecera,
			String gama, String edificio, String zona, String planta) {
		Font fontDatos = new Font(FontFamily.HELVETICA, 7, Font.NORMAL,
				BaseColor.BLACK);

		PdfPTable table = new PdfPTable(8);
		table.setSpacingAfter(5);
		table.setSpacingBefore(10);
		table.setWidthPercentage(100);
		float[] columnWidths = new float[] { 1f, 7f, 1f, 7f, 1f, 3f, 1f, 3f };
		try {
			table.setWidths(columnWidths);
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		table.setHorizontalAlignment(Element.ALIGN_LEFT);

		PdfPCell cell1;
		cell1 = new PdfPCell(new Paragraph(this.appMessageSource.getMessage(
				"prevAnual.gama", null, locale), fontCabecera));
		cell1.setBackgroundColor(BaseColor.LIGHT_GRAY);
		table.addCell(cell1);
		cell1 = new PdfPCell(new Paragraph(gama, fontDatos));
		table.addCell(cell1);

		cell1 = new PdfPCell(new Paragraph(this.appMessageSource.getMessage(
				"prevAnual.edificio", null, locale), fontCabecera));
		cell1.setBackgroundColor(BaseColor.LIGHT_GRAY);
		table.addCell(cell1);
		cell1 = new PdfPCell(new Paragraph(edificio, fontDatos));
		table.addCell(cell1);

		cell1 = new PdfPCell(new Paragraph(this.appMessageSource.getMessage(
				"prevAnual.zona", null, locale), fontCabecera));
		cell1.setBackgroundColor(BaseColor.LIGHT_GRAY);
		table.addCell(cell1);
		cell1 = new PdfPCell(new Paragraph(zona, fontDatos));
		table.addCell(cell1);

		cell1 = new PdfPCell(new Paragraph(this.appMessageSource.getMessage(
				"prevAnual.planta", null, locale), fontCabecera));
		cell1.setBackgroundColor(BaseColor.LIGHT_GRAY);
		table.addCell(cell1);
		cell1 = new PdfPCell(new Paragraph(planta, fontDatos));
		table.addCell(cell1);

		return table;

	}
}
