package controller.facture;

import controller.Controller;
import controller.client.Get_Client_Controller;
import controller.history.Application_Controller;
import org.sig.fw.db.bddc.model.Client;
import org.sig.fw.db.corrida.dao.*;
import org.sig.fw.db.corrida.model.*;
import org.sig.fw.layout.pane.SOptionPane;
import org.sig.fw.utility.date.SDate;
import org.sig.fw.utility.number.NumberTools;
import view.facture.Add_Facture_View;

import java.awt.*;
import java.util.ArrayList;
import java.util.List;

public class Add_Facture_Controller extends Controller
{
	private Add_Facture_View vw_add_facture = null;
	private Get_Client_Controller ctrl_search_client = null;
	
	private List<Add_Facture_Content_Controller> ctrl_facture_contents = new ArrayList<Add_Facture_Content_Controller>();
	
	private Facture facture;
	private List<Rfp> rfps = new ArrayList<Rfp>();

	
	public Add_Facture_Controller(Application_Controller ctrl_application, Commande commande)
	{
		super(ctrl_application);
		
		this.facture = new Facture(commande);
		this.facture.setCreatedDate(new SDate());
		this.facture.setFacturedDate(new SDate());
		this.facture.setProductDate(new SDate());
		this.facture.computeFactureNumber();
		this.facture.setPaymentMode(commande.getPaymentMode());
		this.facture.setCategory(new Definition_DBAO("d").getWithFamily(Definition_DBAO.FACT_CATEGORY, 0));
		this.facture.setResponsible(ctrl_application.getConnectedAccount());
		this.facture.setState(new State(1, "SE", "Sans Etat", Color.white, Color.BLACK, 0));
		
		for(Commande_Content cc : new Commande_Content_DBAO("cc").getAllWithCommande(commande))
		{
			Facture_Content fc = new Facture_Content(
					-1,
					this.facture,
					cc,
					0,
					0,
					0,
					0
					);
			this.ctrl_facture_contents.add(new Add_Facture_Content_Controller(ctrl_application, this, fc));
		}

		this.rfps.add(new Rfp(-1, this.facture, this.facture.getCommande().getCc(), 100.0, false));
		
		this.vw_add_facture = new Add_Facture_View(this);
		this.vw_add_facture.setVisible(true);
		this.ctrl_search_client = new Get_Client_Controller(ctrl_application);
		this.updateTotal();
		this.setSave(false);
	}
	
	public Add_Facture_Controller(Application_Controller ctrl_application, Facture facture)
	{
		super(ctrl_application);

		this.facture = facture;
		List<Facture_Content> fcs = new Facture_Content_DBAO("fc").getAllWithFacture(facture);
		
		for(Facture_Content fc : fcs)
		{
			this.ctrl_facture_contents.add(new Add_Facture_Content_Controller(ctrl_application, this, fc));
		}
		
		this.rfps = new Rfp_DBAO("rfp").getWithFacture(facture);
		
		this.vw_add_facture = new Add_Facture_View(this);
		this.vw_add_facture.setVisible(true);
		this.ctrl_search_client = new Get_Client_Controller(ctrl_application);
		this.vw_add_facture.setTitle("Modifier/Visualiser une Facture - " + getFacture().getCommande().getSociety().getName());
		this.updateTotal();
	}
	
	public void updateData()
	{
		if(this.facture.getDbId() == -1)
		{
			this.facture.setCommande((Commande) new Commande_DBAO("com").getWithId(facture.getCommande().getDbId(), true));
			this.facture.computeFactureNumber();
			this.facture.setPaymentMode(facture.getCommande().getPaymentMode());
			
			ctrl_facture_contents.clear();
			for(Commande_Content cc : new Commande_Content_DBAO("cc").getAllWithCommande(facture.getCommande()))
			{
				Facture_Content fc = new Facture_Content(
						-1,
						this.facture,
						cc,
						0,
						0,
						0,
						0
						);
				this.ctrl_facture_contents.add(new Add_Facture_Content_Controller(ctrl_application, this, fc));
			}
			this.rfps.clear();
			this.rfps.add(new Rfp(-1, this.facture, this.facture.getCommande().getCc(), 100.0, false));
		}
		else
		{

		}
	}
	
	public Add_Facture_View getView()
	{
		return this.vw_add_facture;
	}
	
	public Client searchClient(String value)
	{
		return (Client) this.ctrl_search_client.show(value);
	}	
	
	public Facture getFacture()
	{
		return this.facture;
	}
	
	public List<Add_Facture_Content_Controller> getList()
	{
		return this.ctrl_facture_contents;
	}
	
	public List<Rfp> getRfp()
	{
		return this.rfps;
	}

	public void updateTotal()
	{
		if(this.vw_add_facture != null)
			this.vw_add_facture.calcTotal();
		
		boolean onGroup = false;
		double total_group = 0;
		double total_marche = 0;
		double total_cumule = 0;
		double total_precedent = 0;
		for(Add_Facture_Content_Controller ctrl : ctrl_facture_contents)
		{
			Facture_Content cc = ctrl.getModel();
			if(cc.getCommandeContent().getReference().getTypeId() == 1)
			{
				onGroup = true;
			}
			
			if(cc.getCommandeContent().getReference().getTypeId() == 2)
			{
				ctrl.setAmount(total_marche,total_cumule,total_precedent,total_group);
				total_group = 0;
				total_marche = 0;
				total_cumule = 0;
				total_precedent = 0;
				onGroup = false;
			}
			
			if(onGroup)
			{
				total_group += cc.getAmountHt();
				total_marche += cc.getCommandeContent().getAmountHt();
				total_cumule += cc.getAmountCumule();
				total_precedent += cc.getAmountPrecedent();
			}
		}
	}
	
	public void updateClient()
	{
		ctrl_search_client.updateModel();
	}
	
	public void setSave(boolean isSave)
	{
		this.vw_add_facture.setSave(isSave);
	}
	
	public boolean verification()
	{
		String error = "";
		/*if(facture.getAmountNet() == 0 && error.isEmpty())
		{
			error = "Le montant NET de la commande ne peut être égal à 0 !\n";
		}*/
		
		double percent = 0.0;
		
		for(Rfp rfp : rfps)
		{
			percent += rfp.getPercent();
		}
		
		if(percent != 100)
		{
			error = "La répartition entre client doit être égale à 100% ! \n";
		}
		
		for(Rfp rfp : rfps)
		{
			if(rfp.getPayer().getDbId() == -1)
				error += "Le client " + rfp.getPayer().getBddcClient().getCompany() + " n'a pas de données de facturation associées !\n";
		}
		
		if(!error.isEmpty())
		{
			SOptionPane.showErrorMessage("Enregistrement", error);
			return false;
		}
		
		return true;
	}
	
	public void save()
	{
		if(verification())
		{
			/* CALC ECHEANCE */
			facture.computeEcheance(rfps.get(0).getPayer().getCorridaClient());
			
			if(facture.getDbId() == -1)
			{
				facture.setDbId(new Facture_DBAO("fact").insert(facture));
				List<Facture_Content> contents = new ArrayList<Facture_Content>();
				for(Add_Facture_Content_Controller ctrl : ctrl_facture_contents)
				{
					Facture_Content cc = ctrl.getModel();
					cc.setFacture(facture);
					contents.add(cc);
				}
				
				for(Facture_Content cc : contents)
				{
					cc.setDbId(new Facture_Content_DBAO("fc").insert(cc));
				}
				
				for(Rfp rfp : rfps)
				{
					rfp.setDbId(new Rfp_DBAO("rfp").insert(rfp));
				}
				History history = new History(-1, History_DBAO.FACTURE, facture, ctrl_application.getConnectedAccount(), new SDate(), "Création de la Facture " + facture.getFactureNumber() + " d'un montant NET de " + NumberTools.getNumberFormat(2).format(facture.getAmountNet())+ " €");
				new History_DBAO("h").insert(history);
				
				/* RELANCE VALIDATION FACTURE */
				new Relance_DBAO("rel", -1).insert(Relance.createFactor(facture, rfps.get(0).getPayer()));
			}
			else
			{
				new Facture_DBAO("fact").update(facture);
				
				List<Facture_Content> contents = new ArrayList<Facture_Content>();
				for(Add_Facture_Content_Controller ctrl : ctrl_facture_contents)
				{
					Facture_Content cc = ctrl.getModel();
					cc.setFacture(facture);
					contents.add(cc);
				}
				
				for(Facture_Content cc : contents)
				{
					new Facture_Content_DBAO("fc").update(cc);
				}
				
				List<Rfp> rfp_bds = new Rfp_DBAO("rfp").getWithFacture(facture);
				
				for(Rfp rfp_bd : rfp_bds)
				{
					if(!rfps.contains(rfp_bd))
					{
						new Rfp_DBAO("rfp").delete(rfp_bd);
					}
				}
				
				
				for(Rfp rfp : rfps)
				{
					if(rfp_bds.contains(rfp))
					{
						new Rfp_DBAO("rfp").update(rfp);
					}
					else
					{
						new Rfp_DBAO("rfp").insert(rfp);
					}
				}
				History history = new History(-1, History_DBAO.FACTURE, facture, ctrl_application.getConnectedAccount(), new SDate(), "Modification de la Facture " + facture.getFactureNumber() + " d'un montant NET de " + NumberTools.getNumberFormat(2).format(facture.getAmountNet())+ " €");
				new History_DBAO("h").insert(history);
				
				for(Relance r : new Relance_DBAO("rel", Relance_DBAO.FACTOR).getWithObject(facture))
					new Relance_DBAO("rel", -1).delete(r);
				for(Relance r : new Relance_DBAO("rel", Relance_DBAO.FACTURE).getWithObject(facture))
					new Relance_DBAO("rel", -1).delete(r);
				
				/* VALIDATION FACTURE */
				new Relance_DBAO("rel", -1).insert(Relance.createFactor(facture, rfps.get(0).getPayer()));
			}
			if(getFacture().getDbId() != -1)
			{
				new Facture_DBAO("fact").setLock(getFacture(), null);
			}
			this.ctrl_application.activeUpdate("ADD_FACTURE", facture.getCommande().getDossier().getDbId(), facture.getCommande().getConstructionSite().getDbId());
			this.ctrl_application.openView(Application_Controller.FACTURE_VIEW, facture, null);
			this.vw_add_facture.dispose();
		}
	}
}
