package controller.commande;

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

import org.sig.fw.bddclink.web.BddcBrowserAccess;
import org.sig.fw.db.bddc.dao.Client_DBAO;
import org.sig.fw.db.bddc.dao.Construction_Site_DBAO;
import org.sig.fw.db.bddc.dao.Rsv_DBAO;
import org.sig.fw.db.bddc.dao.Society_DBAO;
import org.sig.fw.db.bddc.model.Client;
import org.sig.fw.db.bddc.model.Construction_Site;
import org.sig.fw.db.bddc.model.Dossier;
import org.sig.fw.db.corrida.dao.Cc_DBAO;
import org.sig.fw.db.corrida.dao.Commande_Content_DBAO;
import org.sig.fw.db.corrida.dao.Commande_DBAO;
import org.sig.fw.db.corrida.dao.History_DBAO;
import org.sig.fw.db.corrida.dao.Reference_DBAO;
import org.sig.fw.db.corrida.dao.State_DBAO;
import org.sig.fw.db.corrida.model.Cc;
import org.sig.fw.db.corrida.model.Commande;
import org.sig.fw.db.corrida.model.Commande_Content;
import org.sig.fw.db.corrida.model.History;
import org.sig.fw.db.corrida.model.Reference;
import org.sig.fw.db.corrida.model.State;
import org.sig.fw.layout.pane.SOptionPane;
import org.sig.fw.utility.date.SDate;
import org.sig.fw.utility.number.NumberTools;

import controller.Controller;
import controller.client.Get_Client_Controller;
import controller.history.Application_Controller;
import controller.reference.Search_Reference_Controller;
import model.Site_Without_Commande;
import view.commande.Add_Commande_View;

public class Add_Commande_Controller extends Controller	
{
	private Add_Commande_View vw_add_commande = null;
	private Get_Client_Controller ctrl_search_client = null;
	private Search_Reference_Controller ctrl_search_reference = null;
	
	private List<Add_Commande_Content_Controller> ctrl_commande_contents = new ArrayList<Add_Commande_Content_Controller>();
	
	private Commande commande;
	
	private boolean isFactured = false;

	
	public Add_Commande_Controller(Application_Controller ctrl_application, Site_Without_Commande mdl_swc)
	{
		super(ctrl_application);
		
		this.commande = new Commande();
		this.commande.setDossier(mdl_swc.getDossier());
		if(new Cc_DBAO("cc").isFacturable(mdl_swc.getClient()))
			this.commande.setCc(new Cc_DBAO("cc").getWithBddcClient(mdl_swc.getClient()));
		else
			this.commande.setCc(new Cc(-1, mdl_swc.getClient(), null));
		this.commande.setConstructionSite(mdl_swc.getConstructionSite());
		this.commande.setState((State) new State_DBAO("s").getWithId(State_DBAO.SANS_ETAT, true));
		this.commande.setCreatedDate(new SDate());
		this.commande.setFacturedDate(new SDate());
		this.commande.setSignatureDate(new SDate());
		this.commande.setResponsible(ctrl_application.getConnectedAccount());
		this.commande.setSociety(mdl_swc.getSociety());
		this.commande.computeCommandeNumber();
		this.commande.setAutoLiquidation(false);
		this.commande.setTrancheNumber(new Construction_Site_DBAO("cs").computeTrancheNumber(mdl_swc.getConstructionSite().getDbId(), mdl_swc.getDossier().getDbId()));
		this.commande.setCommandeReference(new Reference_DBAO("ref").getWithId(1));
		
		this.vw_add_commande = new Add_Commande_View(this);
		this.vw_add_commande.setVisible(true);
		this.ctrl_search_client = new Get_Client_Controller(ctrl_application);
		this.ctrl_search_reference = new Search_Reference_Controller(ctrl_application);
	}
	
	public Add_Commande_Controller(Application_Controller ctrl_application, Dossier dossier, Construction_Site cs)
	{
		super(ctrl_application);
		
		this.commande = new Commande();
		this.commande.setDossier(dossier);
		Client bddc_client = new Client_DBAO("cli").getClientAdju(dossier);
		if(new Cc_DBAO("cc").isFacturable(bddc_client))
			this.commande.setCc(new Cc_DBAO("cc").getWithBddcClient(bddc_client));
		else
			this.commande.setCc(new Cc(-1, bddc_client, null));
		this.commande.setConstructionSite(cs);
		this.commande.setCreatedDate(new SDate());
		this.commande.setFacturedDate(new SDate());
		this.commande.setSignatureDate(new SDate());
		this.commande.setState((State) new State_DBAO("s").getWithId(State_DBAO.SANS_ETAT, true));
		this.commande.setResponsible(ctrl_application.getConnectedAccount());
		this.commande.setSociety(new Society_DBAO("soc").getSocietyWithDossier(dossier));
		this.commande.computeCommandeNumber();
		this.commande.setTrancheNumber(new Construction_Site_DBAO("cs").computeTrancheNumber(cs.getDbId(), dossier.getDbId()));
		this.commande.setCommandeReference(new Reference_DBAO("ref").getWithId(1));
		
		this.vw_add_commande = new Add_Commande_View(this);
		this.vw_add_commande.setVisible(true);
		this.ctrl_search_client = new Get_Client_Controller(ctrl_application);
		this.ctrl_search_reference = new Search_Reference_Controller(ctrl_application);
	}
	
	public Add_Commande_Controller(Application_Controller ctrl_application, Commande commande)
	{
		super(ctrl_application);
		
		this.commande = commande;
		commande.computeReference();
		
		List<Commande_Content> ccs = new Commande_Content_DBAO("cc").getAllWithCommande(commande);
		for(Commande_Content cc : ccs)
		{
			this.ctrl_commande_contents.add(new Add_Commande_Content_Controller(ctrl_application, this, cc));
		}
		
		this.vw_add_commande = new Add_Commande_View(this);
		this.vw_add_commande.setVisible(true);
		this.ctrl_search_client = new Get_Client_Controller(ctrl_application);
		this.vw_add_commande.setTitle("Modifier une Commande - " + getCommande().getSociety().getName());
		this.ctrl_search_reference = new Search_Reference_Controller(ctrl_application);
		updateTotal();
	}
	
	public void setIsFactured(boolean isFactured)
	{
		this.isFactured = isFactured;
	}
	
	public Add_Commande_View getView()
	{
		return this.vw_add_commande;
	}
	
	public Client searchClient(String value)
	{
		return (Client) this.ctrl_search_client.show(value);
	}	
	
	public Reference searchReference(String value)
	{
		return (Reference) this.ctrl_search_reference.show(value);
	}	
	
	public Commande getCommande()
	{
		return this.commande;
	}
	
	public boolean getIsFactured()
	{
		return this.isFactured;
	}
	
	public List<Add_Commande_Content_Controller> getList()
	{
		return this.ctrl_commande_contents;
	}
	
	public void addLine(int index)
	{
		if(index == -1)
			ctrl_commande_contents.add(new Add_Commande_Content_Controller(ctrl_application, this, null));
		else
		{
			ctrl_commande_contents.add(index, new Add_Commande_Content_Controller(ctrl_application, this, null));
		}
		computeContentIndex();
		vw_add_commande.computeContentSize();
	}
	
	public void removeLine(int index)
	{
		ctrl_commande_contents.remove(index);
		computeContentIndex();
		vw_add_commande.computeContentSize();
	}
	
	public void moveLine(int index, int type)
	{
		if(index+type < 0)
			return;
		if(index+type >= ctrl_commande_contents.size())
			return;
		
		Add_Commande_Content_Controller ctrl_commande_content = ctrl_commande_contents.get(index);
		ctrl_commande_contents.remove(index);
		ctrl_commande_contents.add(index+type, ctrl_commande_content);
		
		computeContentIndex();
		vw_add_commande.computeContentSize();
	}
	
	private void computeContentIndex()
	{
		for(int i = 0; i < ctrl_commande_contents.size(); i++)
		{
			ctrl_commande_contents.get(i).getModel().setIndex(i);
		}
	}
	
	public void updateTotal()
	{
		if(this.vw_add_commande == null)
			return;
		this.vw_add_commande.calcTotal();
		boolean onGroup = false;
		double total_group = 0;
		for(Add_Commande_Content_Controller ctrl : ctrl_commande_contents)
		{
			Commande_Content cc = ctrl.getModel();
			if(cc.getReference().getTypeId() == 1)
			{
				onGroup = true;
			}
			
			if(cc.getReference().getTypeId() == 2)
			{
				ctrl.setAmountHt(total_group);
				total_group = 0;
				onGroup = false;
			}
			
			if(onGroup)
			{
				total_group += cc.getAmountHt();
			}
		}
	}
	
	public void updateReference()
	{
		ctrl_search_reference.updateModel();
	}
	
	public void updateClient()
	{
		ctrl_search_client.updateModel();
	}
	
	public void updateCommandeReference()
	{
		for(Add_Commande_Content_Controller ctrl : ctrl_commande_contents)
		{
			ctrl.updateCommandeReference();
		}
	}

	public void setSave(boolean isSave)
	{
		this.vw_add_commande.setSave(isSave);
	}
	
	public boolean verification()
	{
		String error = "";
		if(commande.getAmountNet() == 0 && error.isEmpty())
		{
			error = "Le montant NET de la commande ne peut être égal à 0 !\n";
		}
		
		int decal = 0;
		for(Add_Commande_Content_Controller ctrl : ctrl_commande_contents)
		{
			if(ctrl.getModel().getReference().getTypeId() == 2)
			{
				decal--;
			}
			else if(ctrl.getModel().getReference().getTypeId() == 1)
			{
				decal++;
			}
			
			if(decal < 0 && error.isEmpty())
			{
				error += "Un 'EGRP' (Fin de Groupe) ne peut être placé avant le premier 'GRP' (Début de Groupe) !\n";
			}
			else if(decal > 1 && error.isEmpty())
			{
				error += "Plusieurs 'GRP' (Début de Groupe) se suivent sans être fermés par un 'ERGP' (Fin de Groupe)\n";
			}
		}
		
		if(decal >= 1 && error.isEmpty())
		{
			error += "Au moins 1 'GRP' (Début de Groupe) n'est pas fermé par un 'ERGP' (Fin de Groupe)\n";
		}
		
		if(commande.getCc().getDbId() == -1)
			error += "Le client sélectionné ne possède pas les informations de Facturation nécessaires. Veuillez l'importer dans l'application via le menu 'Ajout -> Client'";
		
		if(!error.isEmpty())
		{
			SOptionPane.showErrorMessage("Enregistrement", error);
			return false;
		}
		
		return true;
	}
	
	public void save()
	{
		if(verification())
		{
			if(commande.getDbId() == -1)
			{
				commande.setDbId(new Commande_DBAO("com").insert(commande));
				
				List<Commande_Content> contents = new ArrayList<Commande_Content>();
				for(Add_Commande_Content_Controller ctrl : ctrl_commande_contents)
				{
					Commande_Content cc = ctrl.getModel();
					cc.setCommande(commande);
					contents.add(cc);
				}
				
				for(Commande_Content cc : contents)
				{
					cc.setDbId(new Commande_Content_DBAO("cc").insert(cc));
				}
				
				History history = new History(-1, History_DBAO.COMMANDE, commande, ctrl_application.getConnectedAccount(), new SDate(), "Création de la Commande " + commande.getCommandeNumber() + " d'un montant NET de " + NumberTools.getNumberFormat(2).format(commande.getAmountNet())+ " €");
				new History_DBAO("h").insert(history);
			}
			else
			{
				new Commande_DBAO("com").update(commande);
				
				List<Commande_Content> contents = new ArrayList<Commande_Content>();
				for(Add_Commande_Content_Controller ctrl : ctrl_commande_contents)
				{
					Commande_Content cc = ctrl.getModel();
					cc.setCommande(commande);
					contents.add(cc);
				}
				
				List<Commande_Content> database_contents = new Commande_Content_DBAO("cc").getAllWithCommande(commande);
				
				for(Commande_Content dcc : database_contents)
				{
					if(!contents.contains(dcc))
					{
						new Commande_Content_DBAO("cc").delete(dcc);
					}
				}
				
				for(Commande_Content cc : contents)
				{
					if(!database_contents.contains(cc))
					{
						cc.setDbId(new Commande_Content_DBAO("cc").insert(cc));
					}
					else
					{
						new Commande_Content_DBAO("cc").update(cc);
					}
				}
				
				History history = new History(-1, History_DBAO.COMMANDE, commande, ctrl_application.getConnectedAccount(), new SDate(), "Modification de la Commande " + commande.getCommandeNumber() + " d'un montant NET de " + NumberTools.getNumberFormat(2).format(commande.getAmountNet())+ " €");
				new History_DBAO("h").insert(history);
			}
			this.vw_add_commande.setSave(true);
			if(getCommande().getDbId() != -1)
			{
				new Commande_DBAO("com").setLock(getCommande(), null);
			}
			this.ctrl_application.activeUpdate("ADD_COMMANDE", commande.getDossier().getDbId(), commande.getConstructionSite().getDbId());
			if(new Rsv_DBAO("rsv").getColor(commande.getConstructionSite(), 44) != null && !new Rsv_DBAO("rsv").getColor(commande.getConstructionSite(), 44).equals(Color.GREEN))
			{
				int reply = SOptionPane.showYesNoMessage("Vignette BDDC", "Voulez-vous ouvrir la vignette 'Sign. Marché' sur BDDC ?");
				
				if(reply == SOptionPane.YES_OPTION)
				{
					new BddcBrowserAccess().goToVignette(commande.getConstructionSite().getDbId(), commande.getDossier().getDbId(),2,44);
				}
			}
			this.ctrl_application.openView(Application_Controller.COMMANDE_VIEW, commande, null);
			this.vw_add_commande.dispose();
		}
	}
}
