package Models.Client;

import Controllers.Client.ListeClient;
import Controllers.Dialog.ShowDialog;
import Controllers.Traitement.Adaptateur;
import Controllers.Traitement.ParametreSystem;
import Controllers.Traitement.contro;
import Models.H2JDBC;
import java.io.UnsupportedEncodingException;
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 ClientDB {
    
    Logger logger = Logger.getLogger(ClientDB.class.getName());
    H2JDBC h2jdbc = new H2JDBC();
    contro clt = new contro();
    ShowDialog SD = new ShowDialog();
    
    public boolean addClient(Client clt)
    {
        String req = "INSERT INTO client (codeclient, cin, nomcomplet, nom, prenom, naissance, telefix, telemobile, adresse, codepostale, mail, sexe, local_nom, date_add ) VALUES ("+clt.getCodeclient()+", "+clt.getCin()+", '"+clt.getNomcomplet()+"', '"+clt.getNom()+"', '"+clt.getPrenom()+"', '"+clt.getNaissance()+"', "+clt.getTelefix()+", "+clt.getTelemobile()+", '"+clt.getAdresse()+"', "+clt.getCodepostal()+", '"+clt.getMail()+"', '"+clt.getSexe()+"', '"+ParametreSystem.NomLocalPC+"', now());";
        int nbr = 0;
        try {
            nbr = h2jdbc.InsertUpdateDeleteInTable(req);
        }catch(SQLException ex){
            System.err.println("addClient Erreur SQL ! \n"+ex.getMessage());
            System.out.println(req);
            if(ParametreSystem.ErrorShowLogger)
            {
                logger.error("ClientDB  : addClient :" + ex.getMessage());
            }
            if(ParametreSystem.ErrorShowDialog)
            {
                ShowDialog.setTitre("Erreur SQL !");
                ShowDialog.setDetail(ex.getMessage()+"\n"+ex.getSQLState());
                SD.ShowAletDialog();
            }
        }
        return (nbr>0);
    }
    
    public boolean updateClient(Client client) throws UnsupportedEncodingException
    {
        String req = "UPDATE client ";
        req += " SET cin = '"+client.getCin()+"',";
        
        req += " nom = '"+client.getNom()+"',";
        req += " prenom = '"+client.getPrenom()+"',";
        req += " naissance = '"+client.getNaissance()+"',";
        req += " telefix = '"+client.getTelefix()+"',";
        
        if(client.getTelemobile() != null){
            req += " nomcomplet = '"+client.getNomcomplet()+"',";
        }
        if(client.getTelemobile() != null){
           req += " telemobile = '"+client.getTelemobile()+"',"; 
        }
        
        if(client.getMail() != null){
            req += " mail = '"+client.getMail()+"',";
        }
        
        
        if(client.getCodepostal() != null){
            req += " codepostale = '"+client.getCodepostal()+"',";
        }
        
        req += " adresse = '"+client.getAdresse()+"',";
        
        
        req += " sexe = '"+client.getSexe()+"' ";
        req += " WHERE (codeclient = '"+client.getCodeclient()+"') and (local_nom = '"+ParametreSystem.NomLocalPC+"');";
        
        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("ClientDB  :  :" + ex.getMessage());
            }
            if(ParametreSystem.ErrorShowDialog)
            {
                ShowDialog.setTitre("Erreur SQL !");
                ShowDialog.setDetail(ex.getMessage()+"\n"+ex.getSQLState());
                SD.ShowAletDialog();
            }
        }
        return (nbr>0);
    }
    
    public Client getClient(String code)
    {
        Client clt = new Client();
        String sql="SELECT *, to_char(naissance, 'dd/mm/yyyy') AS naissance_string FROM client WHERE (codeclient= "+code+") AND (local_nom = '"+ParametreSystem.NomLocalPC+"');";
        try {
            ResultSet resultat = h2jdbc.selectFromDB(sql);
            while (resultat.next()){
                clt.setCodeclient(resultat.getString("codeclient"));
                clt.setCin(resultat.getInt("cin"));
                clt.setNom(resultat.getString("nom"));
                clt.setPrenom(resultat.getString("prenom"));
                clt.setNomcomplet(resultat.getString("nomcomplet"));
                clt.setSexe(resultat.getInt("sexe"));
                clt.setNaissance(resultat.getDate("naissance"));
                clt.setDateNaissanceString(resultat.getString("naissance_string"));
                clt.setAdresse(resultat.getString("adresse"));
                clt.setTelefixString(resultat.getString("telefix"));
                clt.setTelemobileString(resultat.getString("telemobile"));
                clt.setMail(resultat.getString("mail"));
                clt.setCodepostal(resultat.getString("codepostale"));
            }
        } catch(SQLException ex){
            System.err.println("Erreur SQL ! \n"+ex.getMessage());
            System.out.println(sql);
            if(ParametreSystem.ErrorShowLogger)
            {
                logger.error("ClientDB  : getClient :" + ex.getMessage());
            }
            if(ParametreSystem.ErrorShowDialog)
            {
                ShowDialog.setTitre("Erreur SQL !");
                ShowDialog.setDetail(ex.getMessage()+"\n"+ex.getSQLState());
                SD.ShowAletDialog();
            }
        }
        return clt ;
    }
    
    public int getidClient()
    {
        
        int id =0 ;
        String sql="SELECT MAX(codeclient) FROM client WHERE (local_nom = '"+ParametreSystem.NomLocalPC+"');";
        try {
            ResultSet Resultat = h2jdbc.selectFromDB(sql);
            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("ClientDB  :  :" + ex.getMessage());
            }
            if(ParametreSystem.ErrorShowDialog)
            {
                ShowDialog.setTitre("Erreur SQL !");
                ShowDialog.setDetail(ex.getMessage()+"\n"+ex.getSQLState());
                SD.ShowAletDialog();
            }
        }
        return id ;
    }
    
    
    public boolean verifyIdClient(int id)
    {
        boolean result = false;
        String sql="SELECT codeclient FROM client WHERE (codeclient= "+id+") AND (local_nom = '"+ParametreSystem.NomLocalPC+"');";
        try {
            ResultSet resultat = h2jdbc.selectFromDB(sql);
            resultat.last();
            if(resultat.getRow()>0){
                  result= true ;
            }
        } catch(SQLException ex){
            System.err.println("Erreur SQL ! \n"+ex.getMessage());
            System.out.println(sql);
            if(ParametreSystem.ErrorShowLogger)
            {
                logger.error("ClientDB  : verifyIdClient :" + ex.getMessage());
            }
            if(ParametreSystem.ErrorShowDialog)
            {
                ShowDialog.setTitre("Erreur SQL !");
                ShowDialog.setDetail(ex.getMessage()+"\n"+ex.getSQLState());
                SD.ShowAletDialog();
            }
        }
        return result;
    }
    
    public boolean verifyCinClient(int cin)
    {
        int resultCIN = 0;
        String sql="SELECT COUNT(codeclient) FROM client WHERE (cin= "+cin+") AND (local_nom = '"+ParametreSystem.NomLocalPC+"') ;";
        try {
            ResultSet Resultat = h2jdbc.selectFromDB(sql);
            Resultat.next();
            resultCIN = Resultat.getInt(1);
        } catch(SQLException ex){
            System.err.println("Erreur SQL ! \n"+ex.getMessage());
            System.out.println(sql);
            if(ParametreSystem.ErrorShowLogger)
            {
                logger.error("ClientDB  : verifyCinClient :" + ex.getMessage());
            }
            if(ParametreSystem.ErrorShowDialog)
            {
                ShowDialog.setTitre("Erreur SQL !");
                ShowDialog.setDetail(ex.getMessage()+"\n"+ex.getSQLState());
                SD.ShowAletDialog();
            }
        }
        return (resultCIN>0);
    }
    
    /********************************** Initial *******************************/
    public ObservableList<ListeClient> SearchCltPersonneGestion(Integer debut, Integer nbr, String Code, String Cin, String NomComplet, String Nom, String Prenom, String Naissance)
    {
        ObservableList<ListeClient> data = FXCollections.observableArrayList();
        
        String Where = "";
        
        if(!clt.isNumericNotnull(Code)){
            Where += " (codeclient = '"+Adaptateur.addSlashes(Code)+"') AND ";
        }
        
        if(!clt.isNumericNotnull(Cin)){
            Where += " (cin = '"+Adaptateur.addSlashes(Cin)+"') AND ";
        }
        
        if(!clt.isStringNull(NomComplet)){
            Where += " (nomcomplet LIKE '%"+Adaptateur.addSlashes(NomComplet)+"%') AND ";
        }
        
        if(!clt.isStringNull(Nom)){
            Where += " (nom LIKE '%"+Adaptateur.addSlashes(Nom)+"%') AND ";
        }
        
        if(!clt.isStringNull(Prenom)){
            Where += " (prenom LIKE '%"+Adaptateur.addSlashes(Prenom)+"%') AND ";
        }
        
        if(!clt.isStringNull(Naissance)){
            Where += " (CAST(naissance AS DATE) =  '"+Naissance+"') 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 *, to_char(naissance, 'dd/mm/yyyy') AS naissance_string  "
                + "FROM client "
                + Where
                + "ORDER BY codeclient DESC "
                + "LIMIT "+debut+" , "+nbr+" ;";
        
        try {
            ResultSet resultat = h2jdbc.selectFromDB(req);
            while (resultat.next()){
                String codeclient = resultat.getString( "codeclient" );
                String cin = resultat.getString( "cin" );
                String nomcomplet=resultat.getString("nomcomplet");
                String nom=resultat.getString("nom");
                String prenom=resultat.getString("prenom");
                String naissance_str = resultat.getString("naissance_string");
                String adresse=resultat.getString("adresse");
                String telefix = resultat.getString( "telefix" );
                String telemobile = resultat.getString( "telemobile" );
                Integer sexe = resultat.getInt( "sexe" );
                data.add(new ListeClient(codeclient, cin, nomcomplet, nom, prenom, naissance_str, adresse, telefix, telemobile, sexe));
            }
        } catch(SQLException ex){
            System.err.println("SearchCltPersonneGestion Erreur SQL ! \n"+ex.getMessage());
            System.out.println(req);
            if(ParametreSystem.ErrorShowLogger)
            {
                logger.error("ClientDB  : SearchCltPersonneGestion :" + ex.getMessage());
            }
            if(ParametreSystem.ErrorShowDialog)
            {
                ShowDialog.setTitre("Erreur SQL !");
                ShowDialog.setDetail(ex.getMessage()+"\n"+ex.getSQLState());
                SD.ShowAletDialog();
            }
        }
       return data ;
    }
    
    public Integer nbrCltPersonneGestion( String Code, String Cin, String NomComplet, String Nom, String Prenom, String Naissance)
    {
        String Where = "";
        
        if(!clt.isNumericNotnull(Code)){
            Where += " (codeclient = '"+Adaptateur.addSlashes(Code)+"') AND ";
        }
        
        if(!clt.isNumericNotnull(Cin)){
            Where += " (cin = '"+Adaptateur.addSlashes(Cin)+"') AND ";
        }
        
        if(!clt.isStringNull(NomComplet)){
            Where += " (nomcomplet LIKE '%"+Adaptateur.addSlashes(NomComplet)+"%') AND ";
        }
        
        if(!clt.isStringNull(Nom)){
            Where += " (nom LIKE '%"+Adaptateur.addSlashes(Nom)+"%') AND ";
        }
        
        if(!clt.isStringNull(Prenom)){
            Where += " (prenom LIKE '%"+Adaptateur.addSlashes(Prenom)+"%') AND ";
        }
        
        if(!clt.isStringNull(Naissance)){
            Where += " (CAST(naissance AS DATE) =  '"+Naissance+"') 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(codeclient) "+ 
                    " FROM client "+ 
                    Where+" ;"; 
        
        int sommme =0;
        try {
            ResultSet resultat = h2jdbc.selectFromDB(req);
            resultat.next();
            sommme = resultat.getInt(1);
        } catch(SQLException ex){
            System.err.println("nbrCltPersonneGestion Erreur SQL ! \n"+ex.getMessage());
            System.out.println(req);
            if(ParametreSystem.ErrorShowLogger)
            {
                logger.error("ClientDB  : nbrCltPersonneGestion :" + ex.getMessage());
            }
            if(ParametreSystem.ErrorShowDialog)
            {
                ShowDialog.setTitre("Erreur SQL !");
                ShowDialog.setDetail(ex.getMessage()+"\n"+ex.getSQLState());
                SD.ShowAletDialog();
            }
        }
        return sommme ;
    }
    
    public ObservableList<Client> getAllClient()
    {
        ObservableList<Client> data = FXCollections.observableArrayList();
        
        String req="SELECT *, to_char(naissance, 'dd/mm/yyyy') AS naissance_string  FROM client ORDER BY codeclient DESC ; ";
        
        try {
            ResultSet resultat = h2jdbc.selectFromDB(req);
            while (resultat.next()){
                Client client = new Client();
                client.setCodeclient(resultat.getString( "codeclient" ));
                client.setCinString(resultat.getString( "cin" ));
                client.setNomcomplet(resultat.getString("nomcomplet"));
                client.setNom(resultat.getString("nom"));
                client.setPrenom(resultat.getString("prenom"));
                client.setNaissance(resultat.getDate("naissance"));
                client.setAdresse(resultat.getString("adresse"));
                client.setTelefixString(resultat.getString( "telefix" ));
                client.setTelemobileString(resultat.getString( "telemobile" ));
                client.setSexe(resultat.getInt( "sexe" ));
                data.add(client);
            }
        } catch(SQLException ex){
            System.err.println("SearchCltPersonneGestion Erreur SQL ! \n"+ex.getMessage());
            System.out.println(req);
            if(ParametreSystem.ErrorShowLogger)
            {
                logger.error("ClientDB  : getAllClient :" + ex.getMessage());
            }
        }
       return data ;
    }
}
