package Controllers.Caisse;

import Controllers.Traitement.Adaptateur;
import Controllers.Traitement.ParametreSystem;
import Controllers.Traitement.contro;
import Models.Caisse.CaisseDB;
import Models.Caisse.CaisseEntreListe;
import Models.Caisse.CaisseListe;
import javafx.scene.control.ProgressBar;
import java.io.IOException;
import java.net.URL;
import java.time.LocalDate;
import java.util.ResourceBundle;
import org.apache.log4j.Logger;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.concurrent.WorkerStateEvent;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.print.PageLayout;
import javafx.print.PageOrientation;
import javafx.print.PageRange;
import javafx.print.Paper;
import javafx.print.Printer;
import javafx.print.PrinterJob;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
import javafx.scene.text.Text;

/**
 * FXML Controller class
 * @author Maher Ben Tili
 */
public class CaisseEntreController implements Initializable {

    Logger logger = Logger.getLogger(CaisseEntreController.class.getName());
    
    @FXML private AnchorPane  AnchorPaneCaisseClt;
    
    @FXML private ProgressBar ProgressBarCaisseEnterClt;
    
    @FXML private DatePicker DatePickerDebut;
    @FXML private DatePicker DatePickerFin;
    
    @FXML private Text TotalEnter; 
    
    @FXML private CheckBox CheckBoxChequeClt;
    @FXML private CheckBox CheckBoxEspace;
    @FXML private CheckBox CheckBoxCarteBancaire;
    
    @FXML private CheckBox  CheckBoxPaiementTraite ;
    @FXML private CheckBox  CheckBoxVenteComptant  ;
    @FXML private CheckBox  CheckBoxVenteCommandeAvance ;
    @FXML private CheckBox  CheckBoxVenteFaciliteAvance ;
    @FXML private CheckBox  CheckBoxVersementCheque ; //l’encaissement 
    
    @FXML public TableView<CaisseListe> TableViewCaisseCltEnter ;
    
    @FXML private TableColumn<CaisseListe ,String> TabColChequeClt;
    @FXML private TableColumn<CaisseListe ,String> TabColEspace;
    @FXML private TableColumn<CaisseListe ,String> TabColCarteBancaire;
    
    @FXML private TableColumn<CaisseListe ,String> TabColIdCaisse;
    @FXML private TableColumn<CaisseListe ,String> TabColType;
    @FXML private TableColumn<CaisseListe ,String> TabColDate;
    @FXML private TableColumn<CaisseListe ,String> TabColMontant;
    @FXML private TableColumn<CaisseListe ,String> TabColChequeCltNumero;
    @FXML private TableColumn<CaisseListe ,String> TabColChequeCltBanque;
    @FXML private TableColumn<CaisseListe ,String> TabColEspaceNom;
    @FXML private TableColumn<CaisseListe ,String> TabColEspacePrenom;
    @FXML private TableColumn<CaisseListe ,String> TabColCateBancaireNumero;
    @FXML private TableColumn<CaisseListe ,String> TabColCateBancaireBanque;
    
    @FXML private Button ButtonEnter;
    @FXML private Button ButtonPrintCaisseEntre;
    
    private Service<Void> ThreadCaisseEnter;
   
    CaisseDB CaisseDB= new CaisseDB();
    
    ObservableList<CaisseListe> ObsListCaisseCltEnter; 
    ObservableList<CaisseListe> TempoObsListCaisseCltEnter;
    private String DateDebut ;
    private String DateFin;
    
    contro clt = new  contro();
    
    public void getDetailEnterCheck()
    {
        TempoObsListCaisseCltEnter = FXCollections.observableArrayList();
        
        boolean CheckChequeClt = CheckBoxChequeClt.isSelected();
        boolean CheckEspace = CheckBoxEspace.isSelected();
        boolean CheckCarteBancaire= CheckBoxCarteBancaire.isSelected();
        
        boolean CheckPaiementTraite = CheckBoxPaiementTraite.isSelected();
        boolean CheckVenteComptant = CheckBoxVenteComptant.isSelected();
        boolean CheckVenteCommandeAvance = CheckBoxVenteCommandeAvance.isSelected();
        boolean CheckVenteFaciliteAvance = CheckBoxVenteFaciliteAvance.isSelected();
        boolean CheckVersementCheque = CheckBoxVersementCheque.isSelected();
        
        boolean SelectedCheck;
        boolean SelectedCheckEspace;
        boolean SelectedCheckChequeClt;
        boolean SelectedCheckCarteBancaire;
        
        float FloatTotalEnter = 0;
        
        // 0-Vente Comptant   |    1-Vente Facilité Avance  |   2 Vente Commande Avance | 3 traite clt |  4 ChequeClt
        if(ObsListCaisseCltEnter.size()>0){
            int indice = 0;
            while(indice<ObsListCaisseCltEnter.size()){
                
                CaisseListe ListCaisseCltEnter = ObsListCaisseCltEnter.get(indice);
                
                SelectedCheck = false;
                SelectedCheckEspace = false;
                SelectedCheckChequeClt = false;
                SelectedCheckCarteBancaire = false;
                
                //Paiement Espace
                if(CheckEspace && ( (ListCaisseCltEnter.getEspaceNom()!= "") || (ListCaisseCltEnter.getEspacePrenom()!= "")) ){
                    SelectedCheckEspace = true;
                }
                
                //Paiement Chèque
                if(CheckChequeClt && ( (ListCaisseCltEnter.getChequeCltBanque()!= "") || (ListCaisseCltEnter.getChequeCltNumero()!= "")) ){
                    SelectedCheckChequeClt = true;
                }
                
                //Paiement Carte Bancaire
                if(CheckCarteBancaire && ( (ListCaisseCltEnter.getCateBancaireBanque()!= "") || (ListCaisseCltEnter.getCateBancaireNumero()!= "")) ){
                    SelectedCheckCarteBancaire = true;
                }
                
                //0-Vente Comptant
                if(CheckVenteComptant && (ListCaisseCltEnter.getCodeType().equals("0")) && (SelectedCheckEspace || SelectedCheckChequeClt || SelectedCheckCarteBancaire) ){ 
                    SelectedCheck = true; 
                }
                
                //1-Vente Facilité Avance
                if(CheckVenteFaciliteAvance && (ListCaisseCltEnter.getCodeType().equals("1")) && (SelectedCheckEspace || SelectedCheckChequeClt || SelectedCheckCarteBancaire) ){ SelectedCheck = true; }
                
                //2 Vente Commande Avance
                if(CheckVenteCommandeAvance && (ListCaisseCltEnter.getCodeType().equals("2")) && (SelectedCheckEspace || SelectedCheckChequeClt || SelectedCheckCarteBancaire) ){ SelectedCheck = true; }
                
                //3 traite clt
                if(CheckPaiementTraite && (ListCaisseCltEnter.getCodeType().equals("3")) && (SelectedCheckEspace || SelectedCheckChequeClt || SelectedCheckCarteBancaire) ){ SelectedCheck = true; }
                
                //4 ChequeClt
                if(CheckVersementCheque && (ListCaisseCltEnter.getCodeType().equals("4")) && (SelectedCheckEspace || SelectedCheckChequeClt || SelectedCheckCarteBancaire) ){ SelectedCheck = true; }
                
                //5 Vente Sans Facture
                if(CheckVenteComptant && (ListCaisseCltEnter.getCodeType().equals("5")) && (SelectedCheckEspace || SelectedCheckChequeClt || SelectedCheckCarteBancaire) ){ SelectedCheck = true;  }
                
                if(SelectedCheck){
                    FloatTotalEnter += ListCaisseCltEnter.getFloatMontant();
                    TempoObsListCaisseCltEnter.add(ListCaisseCltEnter);
                }
                
                indice++;
            }
            TableViewCaisseCltEnter.setItems(TempoObsListCaisseCltEnter);
            TotalEnter.setText(Adaptateur.FloatToStringEspaceCurrency(FloatTotalEnter));
        }
    }
    

    @Override
    public void initialize(URL url, ResourceBundle rb) {
       
        DatePickerDebut.setValue(LocalDate.now());
        DatePickerFin.setValue(LocalDate.now());
        
        DateDebut = DatePickerDebut.getValue().toString();
        DateFin = DatePickerFin.getValue().toString();
        
        TabColChequeClt.setStyle( "-fx-alignment: CENTER;");TabColChequeClt.getStyleClass().add("Center");
        TabColEspace.setStyle( "-fx-alignment: CENTER;");TabColEspace.getStyleClass().add("Center");
        TabColCarteBancaire.setStyle( "-fx-alignment: CENTER;");TabColCarteBancaire.getStyleClass().add("Center");
        
        TabColIdCaisse.setStyle( "-fx-alignment: CENTER;");TabColIdCaisse.getStyleClass().add("Center");
        TabColIdCaisse.setCellValueFactory(new PropertyValueFactory<CaisseListe, String>("IdCaisseClt"));
        
        TabColType.setStyle( "-fx-alignment: CENTER;");TabColType.getStyleClass().add("Center");
        TabColType.setCellValueFactory(new PropertyValueFactory<CaisseListe, String>("Type"));
        
        TabColDate.setStyle( "-fx-alignment: CENTER;");TabColDate.getStyleClass().add("Center");
        TabColDate.setCellValueFactory(new PropertyValueFactory<CaisseListe, String>("Date"));
        
        TabColMontant.setStyle( "-fx-alignment: CENTER;");TabColMontant.getStyleClass().add("Center");
        TabColMontant.setCellValueFactory(new PropertyValueFactory<CaisseListe, String>("Montant"));
        
        TabColChequeCltNumero.setStyle( "-fx-alignment: CENTER;");TabColChequeCltNumero.getStyleClass().add("Center");
        TabColChequeCltNumero.setCellValueFactory(new PropertyValueFactory<CaisseListe, String>("ChequeCltNumero"));
        
        TabColChequeCltBanque.setStyle( "-fx-alignment: CENTER;");TabColChequeCltBanque.getStyleClass().add("Center");
        TabColChequeCltBanque.setCellValueFactory(new PropertyValueFactory<CaisseListe, String>("ChequeCltBanque"));
        
        TabColEspaceNom.setStyle( "-fx-alignment: CENTER;");TabColEspaceNom.getStyleClass().add("Center");
        TabColEspaceNom.setCellValueFactory(new PropertyValueFactory<CaisseListe, String>("EspaceNom"));
        
        TabColEspacePrenom.setStyle( "-fx-alignment: CENTER;");TabColEspacePrenom.getStyleClass().add("Center");
        TabColEspacePrenom.setCellValueFactory(new PropertyValueFactory<CaisseListe, String>("EspacePrenom"));
        
        TabColCateBancaireNumero.setStyle( "-fx-alignment: CENTER;");TabColCateBancaireNumero.getStyleClass().add("Center");
        TabColCateBancaireNumero.setCellValueFactory(new PropertyValueFactory<CaisseListe, String>("CateBancaireNumero"));
        
        TabColCateBancaireBanque.setStyle( "-fx-alignment: CENTER;");TabColCateBancaireBanque.getStyleClass().add("Center");
        TabColCateBancaireBanque.setCellValueFactory(new PropertyValueFactory<CaisseListe, String>("CateBancaireBanque"));
        
        ButtonEnter.setOnAction(new EventHandler<ActionEvent>() {
            @Override 
            public void handle(ActionEvent actionEvent) {
            try{ 
                DateDebut = DatePickerDebut.getConverter().fromString(DatePickerDebut.getEditor().getText()).toString();
                DateFin = DatePickerFin.getConverter().fromString(DatePickerFin.getEditor().getText()).toString();
                getCaisseEnterThread();
            }catch(Exception ex){}
            
            }
        });
        
        this.FiltreCaisse();
        
        this.CaisseEntrePrintButton();
    }    
    
    private void FiltreCaisse()
    {
        CheckBoxChequeClt.setOnAction(new EventHandler<ActionEvent>(){
            @Override
            public void handle(ActionEvent t) {
                getDetailEnterCheck();
            }
        });
        CheckBoxEspace.setOnAction(new EventHandler<ActionEvent>(){
            @Override
            public void handle(ActionEvent t) {
               getDetailEnterCheck();
            }
        });
        CheckBoxCarteBancaire.setOnAction(new EventHandler<ActionEvent>(){
            @Override
            public void handle(ActionEvent t) {
               getDetailEnterCheck();
            }
        });
        
        CheckBoxPaiementTraite.setOnAction(new EventHandler<ActionEvent>(){
           @Override
           public void handle(ActionEvent t) {
               getDetailEnterCheck();
           }
        });
        CheckBoxVenteComptant.setOnAction(new EventHandler<ActionEvent>(){
           @Override
           public void handle(ActionEvent t) {
               getDetailEnterCheck();
           }
        });
        CheckBoxVenteCommandeAvance.setOnAction(new EventHandler<ActionEvent>(){
           @Override
           public void handle(ActionEvent t) {
               getDetailEnterCheck();
           }
        });
        CheckBoxVenteFaciliteAvance.setOnAction(new EventHandler<ActionEvent>(){
           @Override
           public void handle(ActionEvent t) {
               getDetailEnterCheck();
           }
        });
        
        CheckBoxVersementCheque.setOnAction(new EventHandler<ActionEvent>(){
           @Override
           public void handle(ActionEvent t) {
               getDetailEnterCheck();
           }
        });
        CheckBoxVersementCheque.setOnAction(new EventHandler<ActionEvent>(){
           @Override
           public void handle(ActionEvent t) {
               getDetailEnterCheck();
           }
        });
        
        
    }
    
    
    public void getCaisseEnterThread()
    {
        TotalEnter.setText("--");
        
        DatePickerDebut.setDisable(true);
        DatePickerFin.setDisable(true);
        ButtonEnter.setDisable(true);
        ButtonPrintCaisseEntre.setDisable(true);
        
        ProgressBarCaisseEnterClt.setVisible(true);
        TableViewCaisseCltEnter.setItems(null);
        
        CheckBoxChequeClt.setSelected(true);
        CheckBoxEspace.setSelected(true);
        CheckBoxCarteBancaire.setSelected(true);
    
        CheckBoxPaiementTraite.setSelected(true);
        CheckBoxVenteComptant.setSelected(true);
        CheckBoxVenteCommandeAvance.setSelected(true);
        CheckBoxVenteFaciliteAvance.setSelected(true);
        CheckBoxVersementCheque.setSelected(true);
        
        
        ThreadCaisseEnter = new Service<Void>(){
            @Override
            protected Task<Void> createTask(){
                return new Task<Void>(){
                    @Override
                    protected Void call() throws Exception{
                        ObsListCaisseCltEnter = CaisseDB.GetDataCaisseCltEnter(DateDebut, DateFin);
                        int indice = 0;
                        float FloatTotalEnter = 0;
                        while(indice<ObsListCaisseCltEnter.size()){
                            FloatTotalEnter += ObsListCaisseCltEnter.get(indice).getFloatMontant();
                            indice++;
                        }
                        
                        TotalEnter.setText(Adaptateur.FloatToStringEspaceCurrency(FloatTotalEnter));
                        
                        TempoObsListCaisseCltEnter = ObsListCaisseCltEnter;
                        
                        TableViewCaisseCltEnter.setItems(ObsListCaisseCltEnter);
                        
                        return null;
                    }
                };
            }
	};
        
        ThreadCaisseEnter.setOnSucceeded(new EventHandler<WorkerStateEvent>(){
            @Override
            public void handle(WorkerStateEvent event){
                ProgressBarCaisseEnterClt.setVisible(false);
                DatePickerDebut.setDisable(false);
                DatePickerFin.setDisable(false);
                ButtonEnter.setDisable(false);
                ButtonPrintCaisseEntre.setDisable(false);
            }
        });
        ThreadCaisseEnter.start();
    }
    
    
    private void CaisseEntrePrintButton()
    {
        ButtonPrintCaisseEntre.setOnAction(new EventHandler<ActionEvent>(){
           @Override
           public void handle(ActionEvent t) {
               String strPaiment = "";
                if(CheckBoxChequeClt.isSelected()){ strPaiment += "Chéque | "; }
                if(CheckBoxEspace.isSelected()){ strPaiment += "Espéce | "; }
                if(CheckBoxCarteBancaire.isSelected()){ strPaiment += "Carte Bancaire | "; }
                strPaiment = strPaiment.substring(0, strPaiment.length() - 3);

                String strType = "";
                if(CheckBoxPaiementTraite.isSelected()){ strType += "Traite | "; }
                if(CheckBoxVenteComptant.isSelected()){ strType += "Vente Comptant | "; }
                if(CheckBoxVenteCommandeAvance.isSelected()){ strType += "Vente Commande Avance | "; }
                if(CheckBoxVenteFaciliteAvance.isSelected()){ strType += "Vente Facilité Avance | "; }
                if(CheckBoxVersementCheque.isSelected()){ strType += "Chèque | "; }

                strType = strType.substring(0, strType.length() - 3);

                int SizelistCaisseCltEntert = TempoObsListCaisseCltEnter.size();
                int total = SizelistCaisseCltEntert / 13 + 1 ;
                int page = 0;

                String strEspace; String strCheque; String strCarteBancaire;

                PrinterJob jobPrint = PrinterJob.createPrinterJob();

                jobPrint.getJobSettings().setPageRanges(new PageRange(1, total));

                if (jobPrint.showPrintDialog(null)) 
                {
                    Printer printer = jobPrint.getPrinter();
                    PageLayout pageLayout = printer.createPageLayout(Paper.A4, PageOrientation.LANDSCAPE, Printer.MarginType.DEFAULT);

                    for (int i=0; i<SizelistCaisseCltEntert; i+=13)
                    {
                        try {
                            ObservableList<CaisseEntreListe> listTemp = FXCollections.observableArrayList();
                            
                            for (int j=i; (j<(i+13)) && (j<SizelistCaisseCltEntert); j++)
                            {
                                CaisseListe ListCaisseClt = TempoObsListCaisseCltEnter.get(j);
                                
                                strEspace =""; strCheque=""; strCarteBancaire="";
                                
                                if(!clt.isStringNull(ListCaisseClt.getChequeCltNumero())){
                                    strCheque = ListCaisseClt.getChequeCltNumero()+" - " +ListCaisseClt.getChequeCltBanque();
                                }else if(!clt.isStringNull(ListCaisseClt.getCateBancaireNumero())){
                                    strCarteBancaire = ListCaisseClt.getCateBancaireNumero()+" - "+ListCaisseClt.getCateBancaireBanque();
                                }else{
                                    strEspace = ListCaisseClt.getEspaceNom()+" "+ListCaisseClt.getEspacePrenom();
                                }
                                
                                listTemp.add(new CaisseEntreListe(
                                        ListCaisseClt.getIdCaisseClt(),
                                        ListCaisseClt.getCodeType(),
                                        ListCaisseClt.getType(),
                                        ListCaisseClt.getDate(),
                                        ListCaisseClt.getMontant(),
                                        strCheque,
                                        strEspace,
                                        strCarteBancaire,
                                        ListCaisseClt.getFloatMontant()
                                ));
                            }
                            FXMLLoader fxmlLoaderCaisseEntrePrint = new FXMLLoader(getClass().getResource("/Views/Caisse/CaisseEntrePrint.fxml"));
                            final Node ParentFxmlCaisseEntrePrint = (Node)fxmlLoaderCaisseEntrePrint.load();
                            CaisseEntrePrintController caisseEntrePrintController = fxmlLoaderCaisseEntrePrint.getController();
                            page++;
                            
                            caisseEntrePrintController.setCaisseEntrePrint(
                                    Adaptateur.NormalDateFormat(DateDebut)+" à "+Adaptateur.NormalDateFormat(DateFin),
                                    ParametreSystem.NomLocalPC,
                                    TotalEnter.getText(),
                                    strPaiment,
                                    page+"/"+total,
                                    strType,
                                    listTemp);
                            
                            jobPrint.printPage(pageLayout, ParentFxmlCaisseEntrePrint);
                        } catch (IOException ex) {
                            logger.error("CaisseEntreController  : CaisseEntrePrint.fxml :" + ex.getMessage());
                        }
                    }
                    jobPrint.endJob();
                }
           }
        });
    }
    
    
}
