package controller.payment;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;

import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.PDPageContentStream.AppendMode;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.graphics.image.LosslessFactory;
import org.sig.fw.db.corrida.dao.Commande_DBAO;
import org.sig.fw.db.corrida.dao.Payment_DBAO;
import org.sig.fw.db.corrida.model.Payment;
import org.sig.fw.log.common.LogTools;
import org.sig.fw.spdf.common.PDF;
import org.sig.fw.utility.date.SDate;
import org.sig.fw.utility.number.NumberTools;
import org.sig.fw.utility.number.SMath;

import view.payment.Payment_Pdf_View;

public class Payment_Pdf_Controller extends PDF
{
	private Payment_Pdf_View vw_payment_pdf;
	private Payment payment;
	
	private float page_width = 0;
	private float page_height = 0;
	
	public Payment_Pdf_Controller(Payment payment)
	{
		super();
		this.payment = payment;
		this.vw_payment_pdf = new Payment_Pdf_View(this);
		this.vw_payment_pdf.setVisible(true);
	}

	public void drawPdf()
	{
		new Thread(new Runnable() 
		{
			@Override
			public void run() 
			{
				try
				{	
					vw_payment_pdf.setValue("Création du document", 0);
					createPage();
					vw_payment_pdf.setValue("Ajout de l'entête", 20);
					createLogo();
					vw_payment_pdf.setValue("Calcul du SOLDE", 40);
					createSolde();
					vw_payment_pdf.setValue("Ajout du contenu", 60);
					createContent();
					vw_payment_pdf.setValue("Finalisation du document", 100);
					
					closeStream();
					save(payment.getFacture().getCommande().getDossier().getDirectory()+"\\09-Factures-Caution", "Paiement du " + payment.getDate().getFormattedDate(SDate.FORMAT_FR).replace("/", "-"));
					closeDocument();
				}
				catch (IOException e) 
				{
					LogTools.addErrorLog("PDF02", e);
				}
				vw_payment_pdf.dispose();
			}
		}).start();
	}
	
	private void createPage() throws IOException
	{
		this.page = new PDPage(PDRectangle.A4);
		this.document.addPage(page);
		
        this.page_width = this.page.getMediaBox().getWidth();
        this.page_height = this.page.getMediaBox().getHeight();
        this.contentStream = new PDPageContentStream(document, page, AppendMode.OVERWRITE, false);
	}
	
	
	private void createLogo() throws IOException
	{
		BufferedImage image = null;
		if(payment.getFacture().getCommande().getSociety().getDbId() == 1)
		{
			image = ImageIO.read(Payment_Pdf_Controller.class.getResource("/logo/sondefor_logo.png"));
			this.contentStream.drawImage(LosslessFactory.createFromImage(this.document, image), 10, this.page_height-10-50, 282, 50);
		}
		else if(payment.getFacture().getCommande().getSociety().getDbId() == 2)
		{
			image = ImageIO.read(Payment_Pdf_Controller.class.getResource("/logo/sbf_logo.png"));
			this.contentStream.drawImage(LosslessFactory.createFromImage(this.document, image), 10, this.page_height-10-50, 90, 50);
		}
	}
	
	private void createSolde() throws IOException
	{
		if(SMath.round(new Payment_DBAO("pay").getSumWithDossierAndConstructionSite(payment.getFacture().getCommande().getDossier(), payment.getFacture().getCommande().getConstructionSite()),2) >= SMath.round(new Commande_DBAO("com").getSumOfCommandeWithDossierAndConstructionSite(payment.getFacture().getCommande().getDossier(), payment.getFacture().getCommande().getConstructionSite()),2))
		{
			contentStream.beginText();
			String text = "SOLDE";
			int fontSize = 20;
			float textWidth = bold_font.getStringWidth(text) / 1000 * fontSize;
			float textHeight = bold_font.getFontDescriptor().getFontBoundingBox().getHeight() / 1000 * fontSize;
			contentStream.setFont(bold_font, fontSize);
			contentStream.newLineAtOffset(390, 790);
			contentStream.showText(text);
			contentStream.endText();
			
			contentStream.addRect(380, 780, textWidth+20, textHeight+10);
			contentStream.stroke();
		}
	}
	
	private void createContent() throws IOException
	{
		int fontSize = 15;
		float textHeight = 0;
		String text = "";
		
		int x = 60;
		int y = (int) (this.page_height-150);
		
		int decal = this.drawString(x, y, "Date de Paiement :", bold_font, true) + 3;
		x += decal;
		this.drawString(x, y, payment.getDate().getFormattedDate(SDate.FORMAT_FR), normal_font, false);
		x -= decal;
		
		y -= 40;

		decal = this.drawString(x, y, "Dossier :", bold_font, true) + 3;
		x += decal;
		this.drawString(x, y, payment.getFacture().getCommande().getDossier().getReferenceNumber(), normal_font, false);
		x -= decal;
		
		y -= 18;
		
		this.drawString(x, y, payment.getFacture().getCommande().getDossier().getLocalisation() + " " + payment.getFacture().getCommande().getDossier().getName(), normal_font, false);
		
		y -= 40;
		
		decal = this.drawString(x, y, "Client :", bold_font, true) + 3;
		x += decal;
		this.drawString(x, y, payment.getCc().getBddcClient().getCompany() + " " + payment.getCc().getBddcClient().getAddress().getCity(), normal_font, false);
		x -= decal;
		
		y -= 40;
		
		decal = this.drawString(x, y, "Mode de Paiement :", bold_font, true) + 3;
		x += decal;
		this.drawString(x, y, payment.getPaymentMode().toString(), normal_font, false);
		x -= decal;
		
		y -= 40;
		
		decal = this.drawString(x, y, "Montant :", bold_font, true) + 3;
		x += decal;
		this.drawString(x, y, NumberTools.getNumberFormat(2).format(payment.getAmount()) + " €", normal_font, false);
		x -= decal;
		
		y -= 40;
		
		decal = this.drawString(x, y, "Facture N° :", bold_font, true) + 3;
		x += decal;
		this.drawString(x, y, payment.getFacture().getFactureNumber(), normal_font, false);
		x -= decal;
		
		y -= 40;
		
		text = payment.getObservation();
		int total_width = (int) (this.page_width - 120);
		
	    List<String> lines = new ArrayList<String>();
	    int lastSpace = -1;
	    while (text.length() > 0)
	    {
	        int spaceIndex = text.indexOf(' ', lastSpace + 1);
	        if (spaceIndex < 0)
	            spaceIndex = text.length();
	        String subString = text.substring(0, spaceIndex);
	        float size = fontSize * normal_font.getStringWidth(subString) / 1000;
	        if (size > total_width)
	        {
	            if (lastSpace < 0)
	                lastSpace = spaceIndex;
	            subString = text.substring(0, lastSpace);
	            lines.add(subString);
	            text = text.substring(lastSpace).trim();
	            lastSpace = -1;
	        }
	        else if (spaceIndex == text.length())
	        {
	            lines.add(text);
	            text = "";
	        }
	        else
	        {
	            lastSpace = spaceIndex;
	        }
	    }

	    textHeight = normal_font.getFontDescriptor().getFontBoundingBox().getHeight() / 1000 * fontSize;
	    contentStream.beginText();
	    contentStream.setFont(normal_font, fontSize);
	    contentStream.newLineAtOffset(x, y);
	    for(int i = 0; i < lines.size(); i++)
	    {
	        contentStream.showText(lines.get(i));
	        contentStream.newLineAtOffset(0, -textHeight);
	        y -= textHeight;
	    }
	    contentStream.endText();
	}
	
	private int drawString(int x, int y, String text, PDFont font, boolean isUnderline) throws IOException
	{
		int fontSize = 15;
		this.contentStream.beginText();
		this.contentStream.setFont(font, fontSize);
		float textWidth = font.getStringWidth(text) / 1000 * fontSize;
		contentStream.newLineAtOffset(x, y);
		contentStream.showText(text);
		contentStream.endText();
		
		if(isUnderline)
		{
			contentStream.addRect(x, y-1, textWidth, 0);
			contentStream.stroke();
		}
		
		return (int) textWidth;
	}

	@Override
	public void createDocument() throws IOException {
		// TODO Auto-generated method stub
		
	}
}
