package Models.Client;

import Controllers.Client.ListeClientEntreprise;
import Controllers.Dialog.ShowDialog;
import Controllers.Traitement.Adaptateur;
import Controllers.Traitement.ParametreSystem;
import Controllers.Traitement.contro;
import Models.H2JDBC;
import Models.Home.HomeDB;
import java.sql.ResultSet;
import java.sql.SQLException;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.apache.log4j.Logger;


/**
 * @author Maher Ben Tili
 */
public class ClientEntrepriseDB {
    
    H2JDBC h2jdbc = new H2JDBC();
    Logger logger = Logger.getLogger(HomeDB.class.getName());
    contro clt = new contro();
    ShowDialog SD = new ShowDialog();
    
    public boolean verifyCodeEntreprise(int code)
    {
        int nbr = 0 ;
        
        String sql="SELECT COUNT(*) FROM cltentreprise WHERE (idcliententreprise = "+code+") AND (local_nom = '"+ParametreSystem.NomLocalPC+"');";
        try {
            ResultSet resultat = h2jdbc.selectFromDB(sql);
            resultat.next();
            nbr = resultat.getInt(1);
        } catch(SQLException ex){
            System.err.println("Erreur SQL ! \n"+ex.getMessage());
            System.out.println(sql);
            if(ParametreSystem.ErrorShowLogger)
            {
                logger.error("ClientEntrepriseDB  : verifyCodeEntreprise :" + ex.getMessage());
            }
            if(ParametreSystem.ErrorShowDialog)
            {
                ShowDialog.setTitre("Erreur SQL !");
                ShowDialog.setDetail(ex.getMessage()+"\n"+ex.getSQLState());
                SD.ShowAletDialog();
            }
        }
        
        return (nbr>0) ;
    }
    
    
    
    public ClientEntreprise GetClientEtr(String CodeEtr)
    {
        ClientEntreprise ClientEtr = new ClientEntreprise();
        
        String sql="SELECT * FROM cltentreprise WHERE (idcliententreprise = "+CodeEtr+") AND (local_nom = '"+ParametreSystem.NomLocalPC+"');";
            
        ResultSet resultat = h2jdbc.selectFromDB(sql);
        try {
            while (resultat.next()){
                ClientEtr.setCodeString(resultat.getString("idcliententreprise"));
                ClientEtr.setNom(resultat.getString("nomentrepise"));
                ClientEtr.setGerant(resultat.getString("gerant"));
                ClientEtr.setAdresse(resultat.getString("adresse"));
                ClientEtr.setMail(resultat.getString("mail"));
                ClientEtr.setMatricule(resultat.getString("matricule_fiscale"));
                ClientEtr.setPostal(resultat.getLong("code_postal"));
                ClientEtr.setTele1(resultat.getLong("telefix"));
                ClientEtr.setTele2(resultat.getLong("telefix2"));
                ClientEtr.setFax(resultat.getLong("fax"));
                ClientEtr.setLocalNom(resultat.getString("local_nom"));
                ClientEntrepriseContact EtrContact = new ClientEntrepriseContactDB().getContactByIdEntreprise(resultat.getString("idcliententreprise"));
                ClientEtr.setContact(EtrContact);
            }
        } catch(SQLException ex){
            System.err.println("Erreur SQL ! \n"+ex.getMessage());
            System.out.println(sql);
            if(ParametreSystem.ErrorShowLogger)
            {
                logger.error("ClientEntrepriseDB  : GetClientEtr :" + ex.getMessage());
            }
            if(ParametreSystem.ErrorShowDialog)
            {
                ShowDialog.setTitre("Erreur SQL !");
                ShowDialog.setDetail(ex.getMessage()+"\n"+ex.getSQLState());
                SD.ShowAletDialog();
            }
        }
        
        return ClientEtr ;
    }
        
    public int getidClientEtr()
    {
        int id = -1 ;
        
        String sql = "SELECT MAX(idcliententreprise) FROM cltentreprise WHERE local_nom = '"+ParametreSystem.NomLocalPC+"';";
            
        ResultSet Resultat = h2jdbc.selectFromDB(sql);
        try {
            Resultat.next();
            id = Resultat.getInt(1);
        } catch(SQLException ex){
            System.err.println("Erreur SQL ! \n"+ex.getMessage());
            System.out.println(sql);
            if(ParametreSystem.ErrorShowLogger)
            {
                logger.error("ClientEntrepriseDB : getidClientEtr :" + ex.getMessage());
            }
            if(ParametreSystem.ErrorShowDialog)
            {
                ShowDialog.setTitre("Erreur SQL !");
                ShowDialog.setDetail(ex.getMessage()+"\n"+ex.getSQLState());
                SD.ShowAletDialog();
            }
        }
        
        return  id;
    }

    
    public boolean addEntreprise(ClientEntreprise CltEtr)
    {
        String req = "INSERT INTO cltentreprise (idcliententreprise, nomentrepise, gerant, matricule_fiscale, adresse, telefix, telefix2, fax, code_postal, mail, local_nom, date_add) VALUES ("+CltEtr.getCode()+", '"+CltEtr.getNom()+"', '"+CltEtr.getGerant()+"', '"+CltEtr.getMatricule()+"', '"+CltEtr.getAdresse()+"', "+CltEtr.getTele1()+", "+CltEtr.getTele2()+", "+CltEtr.getFax()+", "+CltEtr.getPostal()+", '"+CltEtr.getMail()+"', '"+ParametreSystem.NomLocalPC+"', now());";
        int nbr = 0;
        try {
            nbr = h2jdbc.InsertUpdateDeleteInTable(req);
        }catch(SQLException ex){
		
            System.err.println("Erreur SQL ! \n"+ex.getMessage());
            System.out.println(req);
			
            if(ParametreSystem.ErrorShowLogger)
            {
                logger.error("ClientEntrepriseDB  : addEntreprise :" + ex.getMessage());
            }		
            if(ParametreSystem.ErrorShowDialog)
            {
                ShowDialog.setTitre("Erreur SQL !");
                ShowDialog.setDetail(ex.getMessage()+"\n"+ex.getSQLState());
                SD.ShowAletDialog();
            }
        }
        return (nbr>0);
    }
    
    
    public boolean updateEntreprise(ClientEntreprise CltEtr)
    {
        String req = "UPDATE cltentreprise ";
        
        req += " SET nomentrepise = '"+CltEtr.getNom()+"',";
        
        if(!clt.isStringNull(CltEtr.getMatricule())){
            req += " matricule_fiscale = '"+CltEtr.getMatricule()+"',";
        }
        if(!clt.isStringNull(CltEtr.getTele2String())){
           req += " telefix2 = '"+CltEtr.getTele2String()+"',";
        }
        if(!clt.isStringNull(CltEtr.getFaxString())){
            req += " fax = '"+CltEtr.getFaxString()+"',";
        }
        if(!clt.isStringNull(CltEtr.getPostalString())){
            req += " code_postal = '"+CltEtr.getPostalString()+"',";
        }
        if(!clt.isStringNull(CltEtr.getMail())){
            req += " mail = '"+CltEtr.getMail()+"',";
        }
        
        req += " adresse = '"+CltEtr.getAdresse()+"',";
        req += " gerant = '"+CltEtr.getGerant()+"',";
        req += " telefix = '"+CltEtr.getTele1String()+"'";
        
        req += "WHERE (idcliententreprise = '"+CltEtr.getCodeString()+"') and (local_nom = '"+CltEtr.getLocalNom()+"');";
        
        int nbrCltentreprise = 0;
        try {
            nbrCltentreprise = h2jdbc.InsertUpdateDeleteInTable(req);
            if(nbrCltentreprise>0){
                return new ClientEntrepriseContactDB().updateEtrContact(CltEtr.getContact());
            }else{
                return false;
            }
        }catch(SQLException ex){
		
            System.err.println("Erreur SQL ! \n"+ex.getMessage());
            System.out.println(req);
			
            if(ParametreSystem.ErrorShowLogger)
            {
                logger.error("ClientEntrepriseDB  : updateEntreprise :" + ex.getMessage());
            }
            if(ParametreSystem.ErrorShowDialog)
            {
                ShowDialog.setTitre("Erreur SQL !");
                ShowDialog.setDetail(ex.getMessage()+"\n"+ex.getSQLState());
                SD.ShowAletDialog();
            }
            return false;
        }
    } 
        
    /********************************** Initial *******************************/
    public ObservableList<ListeClientEntreprise> SearchCltEntrepriseGestion(Integer debut, Integer nbr, String CodeEtr, String NomEtr, String GerantEtr, String MatriculeEtr, String AdresseEtr, String TelephoneEtr)
    {
        ObservableList<ListeClientEntreprise> data = FXCollections.observableArrayList();
        
        String Where = "";
        
        if(!clt.isNumericNotnull(CodeEtr)){
            Where += " (idcliententreprise = '"+Adaptateur.addSlashes(CodeEtr)+"') AND ";
        }
        
        if(!clt.isStringNull(NomEtr)){
            Where += " (nomentrepise LIKE '%"+Adaptateur.addSlashes(NomEtr)+"%') AND ";
        }
        
        if(!clt.isStringNull(GerantEtr)){
            Where += " (gerant LIKE'%"+Adaptateur.addSlashes(GerantEtr)+"%') AND ";
        }
        
        if(!clt.isNumericNotnull(MatriculeEtr)){
            Where += " (matricule_fiscale ='"+Adaptateur.addSlashes(MatriculeEtr)+"') AND ";
        }
        
        if(!clt.isStringNull(AdresseEtr)){
            Where += " (adresse LIKE'%"+Adaptateur.addSlashes(AdresseEtr)+"%') AND ";
        }
        
        if(!clt.isNumericNotnull(TelephoneEtr)){
            Where += " (telefix ='"+Adaptateur.addSlashes(TelephoneEtr)+"') AND ";
        }
        
        if(!Where.equals("")){
            Where = Where.substring(0, Where.length() - 4);
            Where = "WHERE (local_nom = '"+ParametreSystem.NomLocalPC+"') AND " + Where;
        }else{
            Where = "WHERE (local_nom = '"+ParametreSystem.NomLocalPC+"') ";
        }
        
        String req="SELECT * "
                    + "FROM cltentreprise "
                    + Where
                    + "ORDER BY idcliententreprise DESC "
                    + "LIMIT "+debut+" , "+nbr+" ;";
        
        ResultSet resultat = h2jdbc.selectFromDB(req);
        try {
            while (resultat.next())
            {
                String code = resultat.getString("idcliententreprise");
                String nom=resultat.getString("nomentrepise");
                String gerant =resultat.getString("gerant");
                String matricule =resultat.getString("matricule_fiscale");
                String adresse =resultat.getString("adresse");
                String telefix = resultat.getString( "telefix" );
                String telefix2 = resultat.getString( "telefix2" );
                
                data.add(new ListeClientEntreprise(code, nom, gerant, matricule, adresse, telefix, telefix2));
            }
        } catch(SQLException ex){
		
            System.err.println("Erreur SQL ! \n"+ex.getMessage());
            System.out.println(req);
			
            if(ParametreSystem.ErrorShowLogger)
            {
                logger.error("ClientEntrepriseDB  : SearchCltEntrepriseGestion :" + ex.getMessage());
            }
            if(ParametreSystem.ErrorShowDialog)
            {
                ShowDialog.setTitre("Erreur SQL !");
                ShowDialog.setDetail(ex.getMessage()+"\n"+ex.getSQLState());
                SD.ShowAletDialog();
            }
        }
        
       return data ;
    }
    
    public Integer nbrCltEntrepriseGestion(String CodeEtr, String NomEtr, String GerantEtr, String MatriculeEtr, String AdresseEtr, String TelephoneEtr)
    {
        String Where = "";
        
        if(!clt.isNumericNotnull(CodeEtr)){
            Where += " (idcliententreprise ='"+Adaptateur.addSlashes(CodeEtr)+"') AND ";
        }
        
        if(!clt.isStringNull(NomEtr)){
            Where += " (nomentrepise LIKE'%"+Adaptateur.addSlashes(NomEtr)+"%') AND ";
        }
        
        if(!clt.isStringNull(GerantEtr)){
            Where += " (gerant LIKE'%"+Adaptateur.addSlashes(GerantEtr)+"%') AND ";
        }
        
        if(!clt.isNumericNotnull(MatriculeEtr)){
            Where += " (matricule_fiscale ='"+Adaptateur.addSlashes(MatriculeEtr)+"') AND ";
        }
        
        if(!clt.isStringNull(AdresseEtr)){
            Where += " (adresse LIKE'%"+Adaptateur.addSlashes(AdresseEtr)+"%') AND ";
        }
        
        if(!clt.isNumericNotnull(TelephoneEtr)){
            Where += " (telefix ='"+Adaptateur.addSlashes(TelephoneEtr)+"') AND ";
        }
        
        if(!Where.equals("")){
            Where = Where.substring(0, Where.length() - 4);
            Where = "WHERE (local_nom = '"+ParametreSystem.NomLocalPC+"') AND " + Where;
        }else{
            Where = "WHERE (local_nom = '"+ParametreSystem.NomLocalPC+"') ";
        }

        String req=" SELECT COUNT(idcliententreprise) FROM cltentreprise "+Where+" ;"; 
        
        int sommme =0;
        try {
            ResultSet Resultat = h2jdbc.selectFromDB(req);
            Resultat.next();
            sommme = Resultat.getInt(1);
        } catch(SQLException ex){
		
            System.err.println("Erreur SQL ! \n"+ex.getMessage());
            System.out.println(req);
            if(ParametreSystem.ErrorShowLogger)
            {
                logger.error("ClientEntrepriseDB  : nbrCltEntrepriseGestion :" + ex.getMessage());
            }
            if(ParametreSystem.ErrorShowDialog)
            {
                ShowDialog.setTitre("Erreur SQL !");
                ShowDialog.setDetail(ex.getMessage()+"\n"+ex.getSQLState());
                
                SD.ShowAletDialog();
            }
        }
        return sommme ;
    }
 
    public ObservableList<ClientEntreprise> getAllCltEntreprise()
    {
        ObservableList<ClientEntreprise> data = FXCollections.observableArrayList();
        
        String req="SELECT * FROM cltentreprise ORDER BY idcliententreprise DESC ";
        
        ResultSet resultat = h2jdbc.selectFromDB(req);
        try {
            while (resultat.next())
            {
                ClientEntreprise cltEntreprise = new ClientEntreprise();
                cltEntreprise.setCodeString(resultat.getString("idcliententreprise"));
                cltEntreprise.setNom(resultat.getString("nomentrepise"));
                cltEntreprise.setGerant(resultat.getString("gerant"));
                cltEntreprise.setMatricule(resultat.getString("matricule_fiscale"));
                cltEntreprise.setAdresse(resultat.getString("adresse"));
                cltEntreprise.setTele1String(resultat.getString("telefix"));
                cltEntreprise.setTele2String(resultat.getString("telefix2"));
                data.add(cltEntreprise);
            }
        } catch(SQLException ex){
		
            System.err.println("Erreur SQL ! \n"+ex.getMessage());
            System.out.println(req);
            if(ParametreSystem.ErrorShowLogger)
            {
                logger.error("ClientEntrepriseDB  : SearchCltEntrepriseGestion :" + ex.getMessage());
            }
        }
        
       return data ;
    }
}
