package Models.Stock;

import Controllers.Dialog.ShowDialog;
import Controllers.Traitement.ParametreSystem;
import Controllers.Traitement.contro;
import Models.BonLivraisonClt.BonLivraisonCltDB;
import Models.H2JDBC;
import javafx.collections.ObservableList;
import Models.User.User;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.log4j.Logger;

/**
 * @author Maher Ben Tili
 */
public class StockDetailDB {
    
    H2JDBC h2jdbc = new H2JDBC();
    ShowDialog SD = new ShowDialog();
    Logger logger = Logger.getLogger(BonLivraisonCltDB.class.getName());
    contro clt = new contro();
    
    public boolean InsertStockDetail(ObservableList<StockDetail> ListStockDetail)
    {
        for(StockDetail ValStockDetail : ListStockDetail)
        {
            String ReferenceProduit = ValStockDetail.getReference_produit();
            Float Quantite = ValStockDetail.getQuantite();
            String IdBonEntre = ValStockDetail.getId_bon_entre();
            String IdBonSortie = ValStockDetail.getId_bon_sortie();
            String IdBonLivraison = ValStockDetail.getId_bon_livraison();
            String IdBonReception = ValStockDetail.getId_bon_reception();
            String IdFactureFrs = ValStockDetail.getId_facture_frs();
            String IdVenteSansFacture = ValStockDetail.getId_vente_sans_facture();
            
            String DateAdd = "'"+ValStockDetail.getDate_add()+"'";
            if(clt.isStringNull(ValStockDetail.getDate_add())){
                DateAdd = "now()"; 
            }
        
            if( (IdBonEntre == null) || (IdBonEntre.isEmpty()) ){
                IdBonEntre = "NULL";
            }
            
            if( (IdBonSortie == null)  ||  (IdBonSortie.isEmpty()) ){
                IdBonSortie = "NULL";
            }
            
            if( (IdBonLivraison == null) || (IdBonLivraison.isEmpty() ) ){
                IdBonLivraison = "NULL";
            }
            
            if( (IdBonReception == null) ||(IdBonReception.isEmpty()) ){
                IdBonReception = "NULL";
            }
            
            if( (IdFactureFrs == null) ||(IdFactureFrs.isEmpty()) ){
                IdFactureFrs = "NULL";
            }
            
            if( (IdVenteSansFacture == null) ||(IdVenteSansFacture.isEmpty()) ){
                IdVenteSansFacture = "NULL";
            }
            String Query = "INSERT INTO stock_detail (local_nom, reference_produit, quantite, date_add, id_profile, id_bon_entre, id_bon_sortie, id_bon_livraison, id_bon_reception, id_facture_frs, id_vente_sans_facture) VALUES "
                        + "('"+ParametreSystem.NomLocalPC+"', '"+ReferenceProduit+"', '"+Quantite+"', "+DateAdd+", '"+User.idprofile+"', "+IdBonEntre+", "+IdBonSortie+", "+IdBonLivraison+", "+IdBonReception+", "+IdFactureFrs+", "+IdVenteSansFacture+" );";
            
            int nbr = 0;
            try {
                nbr = h2jdbc.InsertUpdateDeleteInTable(Query);
                if(nbr>0){
                    Mouvement(ReferenceProduit, ParametreSystem.NomLocalPC);
                }
            }catch(SQLException ex){
                System.err.println("InsertStockDetail Erreur SQL ! \n"+ex.getMessage());
                System.out.println(Query);
                if(ParametreSystem.ErrorShowLogger)
                {
                    logger.error("StockDetailDB  : InsertStockDetail :" + ex.getMessage());
                }
                if(ParametreSystem.ErrorShowDialog)
                {
                    ShowDialog.setTitre("AddBonLivraisonClt Erreur SQL !");
                    ShowDialog.setDetail(ex.getMessage()+"\n"+ex.getSQLState());
                    SD.ShowAletDialog();
                }
            }
        
        }
        return true;
    }
   
    public void Mouvement(String referenceProd, String localNom)
    {
        String req = "SELECT sum(quantite) FROM stock_detail WHERE (reference_produit LIKE '"+referenceProd+"') AND (local_nom LIKE '"+localNom+"')";
        int NewQuantite ;
        try {
            ResultSet resultat = h2jdbc.selectFromDB(req);
            resultat.next();
            NewQuantite = resultat.getInt(1);
            if(NewQuantite == 0)
            {
                h2jdbc.InsertUpdateDeleteInTable("DELETE FROM stock  WHERE (local_nom LIKE '"+referenceProd+"') AND  (produit_reference LIKE '"+localNom+"');");
            }else{
                String req2 = "SELECT COUNT(*) FROM stock WHERE (produit_reference LIKE '"+referenceProd+"') AND (local_nom LIKE '"+localNom+"')";
                ResultSet resultat2 = h2jdbc.selectFromDB(req2);
                resultat2.next();
                int nbr = resultat2.getInt(1);
                if(nbr == 0){
                    h2jdbc.InsertUpdateDeleteInTable("INSERT INTO stock (local_nom, produit_reference, quantite) VALUES('"+localNom+"', '"+referenceProd+"', "+NewQuantite+");");        
                }else{
                    h2jdbc.InsertUpdateDeleteInTable("UPDATE stock SET quantite="+NewQuantite+" WHERE (local_nom='"+localNom+"') AND (produit_reference='"+referenceProd+"')");
                }
            }
        } catch(SQLException ex){
            System.err.println("Erreur SQL ! \n"+ex.getMessage());
            System.out.println(req);
            if(ParametreSystem.ErrorShowLogger)
            {
                logger.error("StockDetailDB  : Mouvement :" + ex.getMessage());
            }
            if(ParametreSystem.ErrorShowDialog)
            {
                ShowDialog.setTitre("Erreur SQL !");
                ShowDialog.setDetail(ex.getMessage()+"\n"+ex.getSQLState());
                SD.ShowAletDialog();
            }
        }
    }
}
