package Controllers.ChequeClt;

import Controllers.TraiteClt.TraiteCltPrintRetardController;
import Controllers.Traitement.Adaptateur;
import Controllers.Traitement.ParametreSystem;
import Models.ChequeClt.ChequeCltDB;
import Models.ChequeClt.ChequeCltGestionListe;
import Models.Stock.StockDB;
import Models.TraiteClt.TraiteCltDB;
import Models.TraiteClt.TraiteCltGestionListe;
import com.gluonhq.charm.glisten.control.ProgressBar;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.concurrent.WorkerStateEvent;
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.Group;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.text.Text;

/**
 * FXML Controller class
 * @author Maher Ben Tili
 */
public class ChequeCltProvisionController implements Initializable {
    
    @FXML private AnchorPane  AnchorPaneChequeCltProvision;
    
    @FXML private ProgressBar ProgressBarChequeCltProvision;
    
    @FXML private Button ButtonSearchChequeCltProvision;
    @FXML private Button ButtonPrintChequeCltProvision;
    
    @FXML private TableView<ChequeCltGestionListe> TableViewChequeCltAvercer ;
    
    @FXML private TableColumn<ChequeCltGestionListe ,String> TabColNumeroCheque;
    @FXML private TableColumn<ChequeCltGestionListe ,String> TabColBanque;
    @FXML private TableColumn<ChequeCltGestionListe ,String> TabColDateCheque;
    @FXML private TableColumn<ChequeCltGestionListe ,String> TabColMontant;
    @FXML private TableColumn<ChequeCltGestionListe ,String> TabColTypeClt;
    @FXML private TableColumn<ChequeCltGestionListe ,String> TabColNomClt;
    @FXML private TableColumn<ChequeCltGestionListe ,String> TabColPrenomClt;
    
    @FXML private DatePicker DatePickerCheque ;
    @FXML private ChoiceBox ChoiceBoxLocal ;
    
    @FXML private TextField TextFieldBanque ;
    @FXML private TextField TextFieldCodeClt ;
    @FXML private TextField TextFieldCINClt ;
    @FXML private TextField TextFieldNomPrenomClt ;
    
    @FXML private Text ActuellePage ;
    @FXML private Text NbrPage ;
    @FXML private Group nextgroupe ;
    @FXML private Group avancergroupe ;
    @FXML private Group lastgroupe ;        
    @FXML private Group retourgroupe ;
    @FXML private Label LabelCount;
    @FXML private ChoiceBox NbrLigne ;
    
    ObservableList cursors = FXCollections.observableArrayList("10","15","20");
    private Integer nbrligne = 10 ;
    private Integer totalcount = 0;
    private Integer nbrpage = 0;
    private Integer actuellepage = 1;
    Integer position = 0;
    
    ObservableList<ChequeCltGestionListe> ListPrintChequeCltProvision;
    
    private Service<Void> ThreadSearchChequeCltProvision;
    private Service<Void> ThreadPrintChequeCltProvision;
    
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        
        NbrLigne.setItems(cursors);
        NbrLigne.getSelectionModel().selectFirst();
        
        TabColNumeroCheque.setCellValueFactory(new PropertyValueFactory<ChequeCltGestionListe, String>("NumeroCheque"));
        TabColNumeroCheque.setStyle( "-fx-alignment: CENTER; -fx-font-weight:bold; -fx-font-size: 10pt;");
        TabColNumeroCheque.getStyleClass().add("Center");
        
        TabColBanque.setCellValueFactory(new PropertyValueFactory<ChequeCltGestionListe, String>("Banque"));
        TabColBanque.setStyle( "-fx-alignment: CENTER; -fx-font-weight:bold; -fx-font-size: 10pt;");
        TabColBanque.getStyleClass().add("Center");
        
        TabColDateCheque.setCellValueFactory(new PropertyValueFactory<ChequeCltGestionListe, String>("DateCheque"));
        TabColDateCheque.setStyle( "-fx-alignment: CENTER; -fx-font-weight:bold; -fx-font-size: 10pt;");
        TabColDateCheque.getStyleClass().add("Center");
        
        TabColMontant.setCellValueFactory(new PropertyValueFactory<ChequeCltGestionListe, String>("Montant"));
        TabColMontant.setStyle( "-fx-alignment: CENTER; -fx-font-weight:bold; -fx-font-size: 10pt;");
        TabColMontant.getStyleClass().add("Center");
        
        TabColTypeClt.setCellValueFactory(new PropertyValueFactory<ChequeCltGestionListe, String>("TypeClt"));
        TabColTypeClt.setStyle( "-fx-alignment: CENTER; -fx-font-weight:bold; -fx-font-size: 10pt;");
        TabColTypeClt.getStyleClass().add("Center");
        
        
        TabColNomClt.setCellValueFactory(new PropertyValueFactory<ChequeCltGestionListe, String>("NomClt"));
        TabColNomClt.setStyle( "-fx-alignment: CENTER; -fx-font-weight:bold; -fx-font-size: 10pt;");
        TabColNomClt.getStyleClass().add("Center");
        
        TabColPrenomClt.setCellValueFactory(new PropertyValueFactory<ChequeCltGestionListe, String>("PrenomClt"));
        TabColPrenomClt.setStyle( "-fx-alignment: CENTER; -fx-font-weight:bold; -fx-font-size: 10pt;");
        TabColPrenomClt.getStyleClass().add("Center");
        
        ArrayList<String> ListLocale = new StockDB().getAllListLocal();
        ChoiceBoxLocal.getItems().addAll(ListLocale);
        
        ButtonSearchChequeCltProvision.setOnMouseClicked(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent me) {
                SearchChequeCltProvision();
            }
        });
        
        AnchorPaneChequeCltProvision.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent ke) {
                if (ke.getCode().equals(KeyCode.ENTER)) {
                    SearchChequeCltProvision();
                }
            }
        });
        
        GestionSearchChequeCltProvision();
        
        ButtonPrintChequeCltProvision.setOnMouseClicked(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent me) {
                ImprimerChequeCltProvision();
            }
        });
    }    
    
    private void ImprimerChequeCltProvision()
    {
        ProgressBarChequeCltProvision.setVisible(true);
        
        ButtonPrintChequeCltProvision.setDisable(true);
        
        ThreadPrintChequeCltProvision = new Service<Void>(){
            @Override
            protected Task<Void> createTask(){
                return new Task<Void>(){
                    @Override
                    protected Void call() throws Exception{
                        
                        String DateDebut = "";
                        if(DatePickerCheque.getValue() != null){
                            DateDebut = DatePickerCheque.getValue().toString();
                        }    
                        
                        ListPrintChequeCltProvision = new ChequeCltDB().SearchChequeCltProvision(
                                                                                       0, 
                                                                                       0, 
                                                                                       DateDebut,
                                                                                       (String) ChoiceBoxLocal.getValue(),
                                                                                       TextFieldBanque.getText(),
                                                                                       TextFieldCodeClt.getText(), 
                                                                                       TextFieldCINClt.getText(),
                                                                                       TextFieldNomPrenomClt.getText(),
                                                                                       true);
                        
                        return null;
                    }
                };
            }
	};
        
        ThreadPrintChequeCltProvision.setOnSucceeded(new EventHandler<WorkerStateEvent>(){
            @Override
            public void handle(WorkerStateEvent event){
                
                int SizeListeChequeCltProvision = ListPrintChequeCltProvision.size();
                
                System.out.println(SizeListeChequeCltProvision);
                
                int total = SizeListeChequeCltProvision / 15 + 1 ;
                int page = 0;
                
                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<SizeListeChequeCltProvision; i+=15)
                    {
                        try {
                            ObservableList<ChequeCltGestionListe> listTemp = FXCollections.observableArrayList();
                            
                            for (int j=i; (j<(i+15)) && (j<SizeListeChequeCltProvision); j++)
                            {
                                ChequeCltGestionListe ListChequeClt = ListPrintChequeCltProvision.get(j);
                                listTemp.add(new ChequeCltGestionListe(
                                                        ListChequeClt.getIdCheque(),
                                                        ListChequeClt.getNumeroCheque(),
                                                        ListChequeClt.getBanque(),
                                                        ListChequeClt.getDateCheque(),
                                                        ListChequeClt.getMontant(),
                                                        ListChequeClt.getCodeClt(),
                                                        ListChequeClt.getTypeClt(),
                                                        ListChequeClt.getNomClt(),
                                                        ListChequeClt.getPrenomClt(),
                                                        ListChequeClt.getIdFacture(),
                                                        ListChequeClt.getEtat(),
                                                        ListChequeClt.getSource(),
                                                        ListChequeClt.getSelected()
                                                ));
                            }
                
                            FXMLLoader fxmlLoaderChequeCltProvisionPrint = new FXMLLoader(getClass().getResource("/Views/ChequeClt/ChequeCltProvisionPrint.fxml"));
                            final Node ParentFxmlChequeCltProvisionPrint = (Node)fxmlLoaderChequeCltProvisionPrint.load();
                            ChequeCltProvisionPrintController chequeCltProvisionPrintController = fxmlLoaderChequeCltProvisionPrint.getController();
                            page++;
                            
                            chequeCltProvisionPrintController.setChequeCltProvision(Integer.toString(SizeListeChequeCltProvision), page+"/"+total, listTemp);
                            
                            jobPrint.printPage(pageLayout, ParentFxmlChequeCltProvisionPrint);
                        } catch (IOException ex) {
                            System.out.println(ex.getMessage());
                        }
                    }
                    jobPrint.endJob();
                }
                
                ProgressBarChequeCltProvision.setVisible(false);
                ButtonPrintChequeCltProvision.setDisable(false);
            }
        });
        ThreadPrintChequeCltProvision.start();
    }
    
       
/******************************************************************************                                                                             *
 *                                                                              *
 *        Methode last Next TableView                                           *
 * *                                                                            *
 ******************************************************************************/  
    
    private void SearchChequeCltProvision()
    {
        ProgressBarChequeCltProvision.setVisible(true);
        
        ButtonSearchChequeCltProvision.setDisable(true);
        
        ThreadSearchChequeCltProvision = new Service<Void>(){
            @Override
            protected Task<Void> createTask(){
                return new Task<Void>(){
                    @Override
                    protected Void call() throws Exception{
                        
                        position = 0;
                        
                        actuellepage = 1;
                        
                        String DateDebut = "";
                        if(DatePickerCheque.getValue() != null){
                            DateDebut = DatePickerCheque.getValue().toString();
                        }    
                        
                        ObservableList<ChequeCltGestionListe> ListChequeCltProvisions = new ChequeCltDB().SearchChequeCltProvision(
                                                                                       position, 
                                                                                       nbrligne, 
                                                                                       DateDebut,
                                                                                       (String) ChoiceBoxLocal.getValue(),
                                                                                       TextFieldBanque.getText(),
                                                                                       TextFieldCodeClt.getText(), 
                                                                                       TextFieldCINClt.getText(),
                                                                                       TextFieldNomPrenomClt.getText(),
                                                                                       false);
                            
                        TableViewChequeCltAvercer.setItems(ListChequeCltProvisions);
                        
                        totalcount = new ChequeCltDB().nbrChequeCltProvision(DateDebut,
                                                                                       (String) ChoiceBoxLocal.getValue(),
                                                                                       TextFieldBanque.getText(),
                                                                                       TextFieldCodeClt.getText(), 
                                                                                       TextFieldCINClt.getText(),
                                                                                       TextFieldNomPrenomClt.getText());
                        
                        if(totalcount > 0){
                            ActuellePage.setText("1");
                        }else{
                            ActuellePage.setText("0");
                        }
                        
                        if(totalcount % nbrligne==0){ 
                            nbrpage = totalcount / nbrligne ;
                        }
                        else{ 
                            nbrpage = (totalcount / nbrligne) + 1 ; 
                        }
                        NbrPage.setText(Integer.toString(nbrpage));
                        
                        return null;
                    }
                };
            }
	};
        
        ThreadSearchChequeCltProvision.setOnSucceeded(new EventHandler<WorkerStateEvent>(){
            @Override
            public void handle(WorkerStateEvent event){
                ProgressBarChequeCltProvision.setVisible(false);
                ButtonSearchChequeCltProvision.setDisable(false);
                LabelCount.setText(totalcount.toString());
                
            }
        });
        ThreadSearchChequeCltProvision.start();
    }
    
    
    private void NextLastSearchChequeCltProvision(Integer ParmPosition, Integer ParamNbrligne)
    {
        ProgressBarChequeCltProvision.setVisible(true);
        
        ButtonSearchChequeCltProvision.setDisable(true);
        
        ThreadSearchChequeCltProvision = new Service<Void>(){
            @Override
            protected Task<Void> createTask(){
                return new Task<Void>(){
                    @Override
                    protected Void call() throws Exception{
                        
                        String DateDebut = "";
                        if(DatePickerCheque.getValue() != null){
                            DateDebut = DatePickerCheque.getValue().toString();
                        }  
                        
                        ObservableList<ChequeCltGestionListe> ListChequeCltProvisions = new ChequeCltDB().SearchChequeCltProvision(ParmPosition, ParamNbrligne, DateDebut, (String) ChoiceBoxLocal.getValue(), TextFieldBanque.getText(), TextFieldCodeClt.getText(), TextFieldCINClt.getText(), TextFieldNomPrenomClt.getText(), false);
                        
                        TableViewChequeCltAvercer.setItems(ListChequeCltProvisions);
                        
                        return null;
                    }
                };
            }
	};
        
        ThreadSearchChequeCltProvision.setOnSucceeded(new EventHandler<WorkerStateEvent>(){
            @Override
            public void handle(WorkerStateEvent event){
                ProgressBarChequeCltProvision.setVisible(false);
                ButtonSearchChequeCltProvision.setDisable(false);
            }
        });
        ThreadSearchChequeCltProvision.start();
    }
  
    private void GestionSearchChequeCltProvision()
    {
        NbrLigne.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() {

            public void changed(ObservableValue ov,  Number value, Number new_value) {
                nbrligne= Integer.parseInt((String) cursors.get(new_value.intValue()));
                if(totalcount % nbrligne==0){ nbrpage = totalcount / nbrligne ;}
                else{ nbrpage = (totalcount / nbrligne) + 1 ; }
                NbrPage.setText(Integer.toString(nbrpage));
                position=0;
                ActuellePage.setText("1");
                actuellepage=1;
                NextLastSearchChequeCltProvision(position, nbrligne);
            }
        });

        if(totalcount % nbrligne==0){ nbrpage = totalcount / nbrligne ;}
        else{ nbrpage = (totalcount / nbrligne) + 1 ; }
        NbrPage.setText(Integer.toString(nbrpage));


        //next page
        nextgroupe.setOnMousePressed(new EventHandler<MouseEvent>(){
            @Override
            public void handle(MouseEvent event) {
                if(actuellepage<nbrpage)
                {
                    position=position+nbrligne;
                    NextLastSearchChequeCltProvision(position, nbrligne);
                    actuellepage=actuellepage+1 ;
                    ActuellePage.setText(Integer.toString(actuellepage));

                }
            }
        }); 

        //last page
        lastgroupe.setOnMousePressed(new EventHandler<MouseEvent>(){
            @Override
            public void handle(MouseEvent event) {
                if(actuellepage>1)
                {
                    position=position-nbrligne;
                    NextLastSearchChequeCltProvision(position, nbrligne);
                    actuellepage=actuellepage-1 ;
                    ActuellePage.setText(Integer.toString(actuellepage));
                }
            }
        }); 

        //next page avec pas de 5
        avancergroupe.setOnMousePressed(new EventHandler<MouseEvent>(){
            @Override
            public void handle(MouseEvent event) {
                if(actuellepage+3<nbrpage)
                {
                    position=(position+4)+nbrligne;
                    NextLastSearchChequeCltProvision(position, nbrligne);
                    actuellepage=actuellepage+3 ;
                    ActuellePage.setText(Integer.toString(actuellepage));

                }
            }
        });

        //last page avec un pas de -5
        retourgroupe.setOnMousePressed(new EventHandler<MouseEvent>(){
            @Override
            public void handle(MouseEvent event) {
                if(actuellepage-3>1){
                    position=(position-4)-nbrligne;
                    NextLastSearchChequeCltProvision(position, nbrligne);
                    actuellepage=actuellepage-3 ;
                    ActuellePage.setText(Integer.toString(actuellepage));
                }
            }
        });

    }
    
    
}
