package Controllers.TraiteClt;

import Models.Stock.StockDB;
import Models.TraiteClt.TraiteCltDB;
import Models.TraiteClt.TraiteCltGestionListe;
import javafx.scene.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 TraiteCltRetardController implements Initializable {

    @FXML private AnchorPane AnchorPaneTraiteCltRetard;
    
    @FXML private ProgressBar ProgressBarTraiteClt;
    
    @FXML public TableView<TraiteCltGestionListe> TableViewTraiteCltRetard;
    
    @FXML public TableColumn<TraiteCltGestionListe ,String> TabColNumTraite;
    @FXML public TableColumn<TraiteCltGestionListe ,String> TabColDateTraite; 
    @FXML public TableColumn<TraiteCltGestionListe ,String> TabColMontant;
    
    @FXML public TableColumn<TraiteCltGestionListe ,String> TabColFacture;
    @FXML public TableColumn<TraiteCltGestionListe ,String> TabColCodeClt;
    @FXML public TableColumn<TraiteCltGestionListe ,String> TabColLocal;
    @FXML public TableColumn<TraiteCltGestionListe ,String> TabColNomPrenom;
    
    @FXML private Button ButtonSearchTraiteCltRetard;
    @FXML private Button ButtonPrintTraiteCltRetard;

    @FXML private DatePicker DatePickeDebut;
    
    @FXML private TextField TextFieldIdFacture ;
    @FXML private TextField TextFieldCodeClt ;
    @FXML private TextField TextFieldCINClt ;
    @FXML private TextField TextFieldNomClt ;
    @FXML private ChoiceBox ChoiceBoxLocal ;
    
    @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;
    
    private Service<Void> ThreadSearchTraiteCltRetard;
    private Service<Void> ThreadPrintTraiteCltRetard;
    
    ObservableList<TraiteCltGestionListe> ListPrintTraiteCltRetards;
    
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        
        NbrLigne.setItems(cursors);
        NbrLigne.getSelectionModel().selectFirst();
        
        TabColNumTraite.setStyle( "-fx-alignment: CENTER;");TabColNumTraite.getStyleClass().add("Center");
        TabColNumTraite.setCellValueFactory(new PropertyValueFactory<TraiteCltGestionListe, String>("NumTraite"));
        
        TabColDateTraite.setStyle( "-fx-alignment: CENTER;");TabColDateTraite.getStyleClass().add("Center");
        TabColDateTraite.setCellValueFactory(new PropertyValueFactory<TraiteCltGestionListe, String>("DateTraite"));
        
        TabColMontant.setStyle( "-fx-alignment: CENTER;");TabColMontant.getStyleClass().add("Center");
        TabColMontant.setCellValueFactory(new PropertyValueFactory<TraiteCltGestionListe, String>("Montant"));
       
        TabColFacture.setStyle( "-fx-alignment: CENTER;");TabColFacture.getStyleClass().add("Center");
        TabColFacture.setCellValueFactory(new PropertyValueFactory<TraiteCltGestionListe, String>("Facture"));
        
        TabColCodeClt.setStyle( "-fx-alignment: CENTER;");TabColCodeClt.getStyleClass().add("Center");
        TabColCodeClt.setCellValueFactory(new PropertyValueFactory<TraiteCltGestionListe, String>("CodeClt"));
        
        TabColLocal.setStyle( "-fx-alignment: CENTER;");TabColLocal.getStyleClass().add("Center");
        TabColLocal.setCellValueFactory(new PropertyValueFactory<TraiteCltGestionListe, String>("TypeClient"));
        
        TabColNomPrenom.setStyle( "-fx-alignment: CENTER;");TabColNomPrenom.getStyleClass().add("Center");
        TabColNomPrenom.setCellValueFactory(new PropertyValueFactory<TraiteCltGestionListe, String>("NomPrenom"));
        
        ArrayList<String> ListLocale = new StockDB().getAllListLocal();
        ChoiceBoxLocal.getItems().addAll(ListLocale);
        
        ButtonSearchTraiteCltRetard.setOnMouseClicked(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent me) {
                //SearchTraiteCltRetard();
            }
        });
        
        AnchorPaneTraiteCltRetard.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent ke) {
                if (ke.getCode().equals(KeyCode.ENTER)) {
                    SearchTraiteCltRetard();
                }
            }
        });
        
        ButtonPrintTraiteCltRetard.setOnMouseClicked(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent me) {
                ImprimerTraiteCltRetard();
            }
        });
        
        GestionSearchTraiteCltRetard();
    }   
    
    
    private void ImprimerTraiteCltRetard()
    {
        ProgressBarTraiteClt.setVisible(true);
        
        ButtonPrintTraiteCltRetard.setDisable(true);
        
        ThreadPrintTraiteCltRetard = new Service<Void>(){
            @Override
            protected Task<Void> createTask(){
                return new Task<Void>(){
                    @Override
                    protected Void call() throws Exception{
                        
                        String DateDebut = "";
                        if(DatePickeDebut.getValue() != null){
                            DateDebut = DatePickeDebut.getValue().toString();
                        }
                        
                        ListPrintTraiteCltRetards = new TraiteCltDB().SearchTraiteCltRetard(0, 0, DateDebut, TextFieldIdFacture.getText(), (String) ChoiceBoxLocal.getValue(), TextFieldCodeClt.getText(), TextFieldCINClt.getText(), TextFieldNomClt.getText(), true);
                        
                        return null;
                    }
                };
            }
	};
        
        ThreadPrintTraiteCltRetard.setOnSucceeded(new EventHandler<WorkerStateEvent>(){
            @Override
            public void handle(WorkerStateEvent event){
                
                int SizeListeTraiteCltGestion = ListPrintTraiteCltRetards.size();
                int total = SizeListeTraiteCltGestion / 16 + 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<SizeListeTraiteCltGestion; i+=16)
                    {
                        try {
                            ObservableList<TraiteCltGestionListe> listTemp = FXCollections.observableArrayList();
                            
                            for (int j=i; (j<(i+16)) && (j<SizeListeTraiteCltGestion); j++)
                            {
                                TraiteCltGestionListe ListCaisseClt = ListPrintTraiteCltRetards.get(j);
                                listTemp.add(new TraiteCltGestionListe(
                                                        ListCaisseClt.getNumTraite(),
                                                        ListCaisseClt.getEtat(),
                                                        ListCaisseClt.getFacture(),
                                                        ListCaisseClt.getCodeClt(),
                                                        ListCaisseClt.getTypeClient(),
                                                        ListCaisseClt.getNomPrenom(),
                                                        ListCaisseClt.getDateTraite(),
                                                        ListCaisseClt.getDatePayer(),
                                                        ListCaisseClt.getMontant(),
                                                        ListCaisseClt.getMontantFloat()
                                                ));
                            }
                
                            FXMLLoader fxmlLoaderTraiteCltPrintRetard = new FXMLLoader(getClass().getResource("/Views/TraiteClt/TraiteCltPrintRetard.fxml"));
                            final Node ParentFxmlTraiteCltPrintRetard = (Node)fxmlLoaderTraiteCltPrintRetard.load();
                            TraiteCltPrintRetardController traiteCltPrintRetardController = fxmlLoaderTraiteCltPrintRetard.getController();
                            page++;
                            
                            traiteCltPrintRetardController.setTraiteCltPrintRetard(
                                    Integer.toString(SizeListeTraiteCltGestion),
                                    page+"/"+total,
                                    listTemp);
                            
                            jobPrint.printPage(pageLayout, ParentFxmlTraiteCltPrintRetard);
                        } catch (IOException ex) {
                            System.out.println(ex.getMessage());
                        }
                    }
                    jobPrint.endJob();
                }
                
                System.out.println(ListPrintTraiteCltRetards.size());
                ProgressBarTraiteClt.setVisible(false);
                ButtonPrintTraiteCltRetard.setDisable(false);
            }
        });
        ThreadPrintTraiteCltRetard.start();
    }
    
        
/******************************************************************************                                                                             *
 *                                                                              *
 *        Methode last Next TableView                                           *
 * *                                                                            *
 ******************************************************************************/  
    
    private void SearchTraiteCltRetard()
    {
        ProgressBarTraiteClt.setVisible(true);
        
        ButtonSearchTraiteCltRetard.setDisable(true);
        
        ThreadSearchTraiteCltRetard = 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(DatePickeDebut.getValue() != null){
                            DateDebut = DatePickeDebut.getValue().toString();
                        }    
                        
                        ObservableList<TraiteCltGestionListe> ListTraiteCltRetards = new TraiteCltDB().SearchTraiteCltRetard(
                                                                                       position, 
                                                                                       nbrligne, 
                                                                                       DateDebut,
                                                                                       TextFieldIdFacture.getText(), 
                                                                                       (String) ChoiceBoxLocal.getValue(),
                                                                                       TextFieldCodeClt.getText(), 
                                                                                       TextFieldCINClt.getText(),
                                                                                       TextFieldNomClt.getText(),
                                                                                       false);
                            
                        TableViewTraiteCltRetard.setItems(ListTraiteCltRetards);
                        
                        totalcount = new TraiteCltDB().nbrTraiteCltRetard(DateDebut,
                                                                           TextFieldIdFacture.getText(), 
                                                                           (String) ChoiceBoxLocal.getValue(),
                                                                           TextFieldCodeClt.getText(), 
                                                                           TextFieldCINClt.getText(),
                                                                           TextFieldNomClt.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;
                    }
                };
            }
	};
        
        ThreadSearchTraiteCltRetard.setOnSucceeded(new EventHandler<WorkerStateEvent>(){
            @Override
            public void handle(WorkerStateEvent event){
                ProgressBarTraiteClt.setVisible(false);
                ButtonSearchTraiteCltRetard.setDisable(false);
                LabelCount.setText(totalcount.toString());
                
            }
        });
        ThreadSearchTraiteCltRetard.start();
    }
    
    
    private void NextLastSearchTraiteCltRetard(Integer ParmPosition, Integer ParamNbrligne)
    {
       ProgressBarTraiteClt.setVisible(true);
        
        ButtonSearchTraiteCltRetard.setDisable(true);
        
        ThreadSearchTraiteCltRetard = new Service<Void>(){
            @Override
            protected Task<Void> createTask(){
                return new Task<Void>(){
                    @Override
                    protected Void call() throws Exception{
                        
                        String DateDebut = "";
                        if(DatePickeDebut.getValue() != null){
                            DateDebut = DatePickeDebut.getValue().toString();
                        } 
                        
                        ObservableList<TraiteCltGestionListe> ListTraiteCltRetards = new TraiteCltDB().SearchTraiteCltRetard(ParmPosition, 
                                                                                                                            ParamNbrligne,
                                                                                                                            DateDebut,
                                                                                                                            TextFieldIdFacture.getText(), 
                                                                                                                            (String) ChoiceBoxLocal.getValue(),
                                                                                                                            TextFieldCodeClt.getText(), 
                                                                                                                            TextFieldCINClt.getText(),
                                                                                                                            TextFieldNomClt.getText(),
                                                                                                                            false );
                        
                        TableViewTraiteCltRetard.setItems(ListTraiteCltRetards);
                        
                        return null;
                    }
                };
            }
        };
        
        ThreadSearchTraiteCltRetard.setOnSucceeded(new EventHandler<WorkerStateEvent>(){
            @Override
            public void handle(WorkerStateEvent event){
                ProgressBarTraiteClt.setVisible(false);
                ButtonSearchTraiteCltRetard.setDisable(false);
            }
        });
        ThreadSearchTraiteCltRetard.start();
    }
  
    private void GestionSearchTraiteCltRetard()
    {
        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;
                NextLastSearchTraiteCltRetard(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;
                    NextLastSearchTraiteCltRetard(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;
                    NextLastSearchTraiteCltRetard(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;
                    NextLastSearchTraiteCltRetard(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;
                    NextLastSearchTraiteCltRetard(position, nbrligne);
                    actuellepage=actuellepage-3 ;
                    ActuellePage.setText(Integer.toString(actuellepage));
                }
            }
        });

    }
}
