package controler.recherche;

import java.math.BigDecimal;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import view.vueRechercheFacture.VueRechercheFacture;
import language.Language;
import tool.regEx.Adresse;
import view.vueFacture.VueFacture;
import commander.Commander;
import controler.Message;
import database.crud.AdresseCrud;
import database.crud.ArticleCrud;
import database.crud.ChambreCrud;
import database.crud.ClientCrud;
import database.crud.FactureCrud;
import database.crud.TaxeCrud;
import database.crud.TelephoneCrud;
import database.crud.VilleCrud;
import database.crud.reservation.ReservationCrud;
import database.crud.vente.LocationChambreCrud;
import database.crud.vente.VenteArticleCrud;
import database.crud.vente.VenteCrud;
import database.dataset.Article;
import database.dataset.Chambre;
import database.dataset.Client;
import database.dataset.Facture;
import database.dataset.Location_chambre;
import database.dataset.Reservation;
import database.dataset.Taxe;
import database.dataset.Telephone;
import database.dataset.Vente;
import database.dataset.Vente_article;
import database.dataset.Ville;
import database.migration.SqlFactory;

/**
 * 
 * @author Alfredo Toyo et Jonathan Guertin
 *
 */
public class ControlerRechercheFacture {
	public ControlerRechercheFacture() {
		
	}
	public static final Message reveil = new Message(){
		public void trigger(Object caster) throws Exception {
			recherche.trigger(caster);
		}
	};
	
	public static final Message recherche = new Message(){
		public void trigger(Object caster) throws Exception {
			if (!(caster instanceof VueRechercheFacture))
				return;
			VueRechercheFacture vue = (VueRechercheFacture)caster;
			Connection connection = Commander.getInstance().getConnectionBD();
			
			FactureCrud factureCrud = new FactureCrud(connection);
			ClientCrud  clientCrud  = new ClientCrud(connection);

			String numeroFacture   = vue.getTextFieldNumero();
			String nomClient       = vue.getTextFieldNomClient();
			String prenomClient    = vue.getTextFieldPrenomClient();
			String numeroFermeture = vue.getTextFieldNumeroFermeture();
			String date            = vue.getDateFieldDate();
			
			List<Facture> factures = factureCrud.readAllLike(numeroFacture, nomClient, prenomClient, numeroFermeture, "", "", date, "");

			vue.clearFacture();
			
			for(Facture facture : factures){
				Client client = clientCrud.readById(facture.getClient_fk_id());
				String montant = SqlFactory.queryOne(connection, "SELECT SUM(sous_total+tps+tvq+hebergement) FROM `view_vente_total` WHERE facture_fk_id="+facture.getFacture_p_id()+" GROUP BY facture_fk_id").toString();
				vue.addLineToTableFacture(facture.getFacture_p_id(), 
						                  facture.getFermeture_fk_id(), 
						                  client.getClient_nom(), 
						                  client.getClient_prenom(), 
						                  facture.getFacture_jour().toString(), 
						                  montant.replaceFirst("000$", "")+"$", 
						                  facture.getFacture_commentaire());
			}
		}
	};
	
	public static final Message modifier = new Message(){
		public void trigger(Object caster) throws Exception {
			if (!(caster instanceof VueRechercheFacture))
				return;
			VueRechercheFacture vue = (VueRechercheFacture)caster;
			
			if(!vue.hasRowSelected())
				return;
			
			Connection connection = Commander.getInstance().getConnectionBD();
			
			Language lang = Commander.getInstance().getLanguage();
			VueFacture vueDest = (VueFacture)Commander.getInstance().getVuePrincipale().setSelectedTab(lang.getPrincipaleReception(), lang.getReceptionFacture());
			
			vueDest.ClearTableReservation();
			vueDest.ClearTableVente();
			
			int facture_id = vue.getSelectedFacture(),
						 j = 0,
						 k = 0;
			
			BigDecimal tps,
					   tvq,
					   total = BigDecimal.ZERO;
			
			vueDest.setFacture_id(vue.getSelectedFacture());
			
			FactureCrud factureCrud = new FactureCrud(connection);
			VenteCrud venteCrud = new VenteCrud(connection);
			LocationChambreCrud locationChambreCrud = new LocationChambreCrud(connection);
			ReservationCrud reservationCrud = new ReservationCrud(connection);
			ArticleCrud articleCrud = new ArticleCrud(connection);
			TaxeCrud taxeCrud = new TaxeCrud(connection);
			VenteArticleCrud venteArticleCrud = new VenteArticleCrud(connection);
			ClientCrud clientCrud = new ClientCrud(connection);
			AdresseCrud adresseCrud = new AdresseCrud(connection);
			TelephoneCrud telephoneCrud = new TelephoneCrud(connection);
			VilleCrud villeCrud = new VilleCrud(connection);
			ChambreCrud chambreCrud = new ChambreCrud(connection);
			
			Chambre chambre;
			Facture facture = factureCrud.readById(facture_id);
			List<Vente> vente = venteCrud.readByfacture_fk(facture_id);
			Client client = clientCrud.readById(facture.getClient_fk_id());
			Adresse adresse = adresseCrud.readById(client.getAdresse_fk_id());
			Ville ville = villeCrud.readById(adresse.getVille_fk_id());
			List<Telephone> telephone = telephoneCrud.readByFk_client(client.getClient_p_id());
			
			for(int i=0;i < vente.size();i++)
			{				
				Article article = articleCrud.readById(vente.get(i).getArticle_fk_id());
				if(article.getCategorie_fk_id() == 1 || article.getCategorie_fk_id() == 2)
				{
					
					if(locationChambreCrud.HasId(vente.get(i).getVente_p_id()) == true)
					{
						Location_chambre locationChambre = locationChambreCrud.readById(vente.get(i).getVente_p_id());
						Reservation reservation = reservationCrud.readById(locationChambre.getReservation_fk_id());					
						chambre = chambreCrud.readById(reservation.getChambre_fk_id());
						
						vueDest.addRowTableReservation(new String[]{reservation.getReservation_debut().toString(), 
																reservation.getReservation_fin().toString(),
																String.valueOf(chambre.getChambre_numero()),
																article.getArticle_code()});
						
						vueDest.add_ReservationId(reservation.getReservation_p_id());
					}
					else
					{
						vueDest.addRowTableReservation(new String[]{"1981-01-01", "1981-01-01", "", ""});
						vueDest.add_ReservationId(0);
					}	
					
					List<Article> articleIndividuel = articleCrud.readByFk_categorie(1);
					List<Article> articleGroupe = articleCrud.readByFk_categorie(2);
					
					List<Article> articleAll = new ArrayList<Article>();
					
					for(int a=0;a<articleIndividuel.size();a++)
					{
						if(articleIndividuel.get(a).isArticle_actif())
						{
							articleAll.add(articleIndividuel.get(a));
						}				
					}
					
					for(int b=0;b<articleGroupe.size();b++)
					{
						if(articleGroupe.get(b).isArticle_actif())
						{
							articleAll.add(articleGroupe.get(b));
						}
					}
					
					for(int a=0;a<articleAll.size();a++)
					{
						vueDest.addPromotionValueAtTableReservation(j, articleAll.get(a).getArticle_code());
					}
					
					vueDest.setPromotionValueAtTableReservation(j, article.getArticle_code());
					
					Taxe taxe = taxeCrud.readById(facture.getTaxe_fk_id());
					tps = ((vente.get(i).getVente_prix().multiply(taxe.getTaxe_tps())));
					tvq = ((vente.get(i).getVente_prix().add(tps)).multiply(taxe.getTaxe_tvq()));
					
					vueDest.setPrixValueAtTableReservation(j, vente.get(i).getVente_prix());
					vueDest.setTPSValueAtTableReservation(j, tps);
					vueDest.setTVQValueAtTableReservation(j, tvq);
					vueDest.setTotalValueAtTableReservation(j, (vente.get(i).getVente_prix().add(tps)).add(tvq));
					
					vueDest.add_ReservationVenteId(vente.get(i).getVente_p_id());
					total = total.add((vente.get(i).getVente_prix().add(tps)).add(tvq));

					j++;
				}
				else
				{
					Taxe taxe = taxeCrud.readById(facture.getTaxe_fk_id());
					Vente_article venteArticle = venteArticleCrud.readById(vente.get(i).getVente_p_id());
					
					List<Article> articleDepanneur = articleCrud.readByFk_categorie(3);
					List<Article> articleRestaurant = articleCrud.readByFk_categorie(4);
					List<Article> articleAdministration = articleCrud.readByFk_categorie(5);
					
					List<Article> articleAll = new ArrayList<Article>();
					
					for(int a=0;a<articleDepanneur.size();a++)
					{
						if(articleDepanneur.get(a).isArticle_actif())
						{
							articleAll.add(articleDepanneur.get(a));
						}				
					}
					
					for(int b=0;b<articleRestaurant.size();b++)
					{
						if(articleRestaurant.get(b).isArticle_actif())
						{
							articleAll.add(articleRestaurant.get(b));
						}
					}
					
					for(int a=0;a<articleAdministration.size();a++)
					{
						if(articleAdministration.get(a).isArticle_actif())
						{
							articleAll.add(articleAdministration.get(a));
						}
					}
					
					tps = ((vente.get(i).getVente_prix().multiply(new BigDecimal(venteArticle.getVente_article_quantite()))).multiply(taxe.getTaxe_tps()));
					tvq = ((vente.get(i).getVente_prix().multiply(new BigDecimal(venteArticle.getVente_article_quantite()))).add(tps)).multiply(taxe.getTaxe_tvq());
					
					vueDest.addRowTableVente(vente.get(i).getVente_jour().toString());
					
					for(int a=0;a<articleAll.size();a++)
					{
						vueDest.addArticleValueAtTableVente(k, articleAll.get(a).getArticle_code());
					}
					
					vueDest.setArticleValueAtTableVente(k, article.getArticle_code());
					vueDest.setPrixValueAtTableVente(k, vente.get(i).getVente_prix());
					vueDest.setNombreValueAtTableVente(k, venteArticle.getVente_article_quantite());
					vueDest.setSousTotalValueAtTableVente(k, vente.get(i).getVente_prix().multiply(new BigDecimal(venteArticle.getVente_article_quantite())));
					vueDest.setTPSValueAtTableVente(k, tps);
					vueDest.setTVQValueAtTableVente(k, tvq);
					vueDest.setTotalValueAtTableVente(k, ((vente.get(i).getVente_prix().multiply(new BigDecimal(venteArticle.getVente_article_quantite()))).add(tps)).add(tvq));
					
					vueDest.add_VenteId(vente.get(i).getVente_p_id());
					total = total.add(((vente.get(i).getVente_prix().multiply(new BigDecimal(venteArticle.getVente_article_quantite()))).add(tps)).add(tvq));
					
					k++;
				}
			}
			
			vueDest.setPrenom(client.getClient_prenom());
			vueDest.setTxtNom(client.getClient_nom());
			vueDest.setCodePostal(adresse.getAdresse_codepostal());
			
			for(int i=0;i<telephone.size();i++)
			{
				vueDest.setTelephone(telephone.get(i).getTelephone_numero());
			}
			
			vueDest.setTxtAdresse(adresse.getadresse_no_rue_app());
			vueDest.setVille(ville.getVille_nom());
			vueDest.setPays(ville.getVille_pays());
			vueDest.setProvince(ville.getVille_province());
			vueDest.setAreaParticularite(facture.getFacture_commentaire());
			vueDest.setAreaCommentaire(client.getClient_commentaire());
			vueDest.setTotal(total);
			
			vueDest.setEnabled(true);
		}
	};
}
