package Controllers.ChequeClt;

import Models.ChequeClt.ChequeCltDB;
import Models.ChequeClt.ChequeCltGestionListe;
import javafx.scene.control.ProgressBar;
import java.io.IOException;
import java.net.URL;
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.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
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.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.util.Callback;

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

    @FXML private AnchorPane  PaneChequeCltGestion;
    
    @FXML private ProgressBar ProgressBarChequeCltGestion;
    
    @FXML private Button ButtonSearchChequeCltGestion;
    
    @FXML public TableView<ChequeCltGestionListe> TableViewChequeCltGestion ;
    
    @FXML private TableColumn TabColChequeClt;
    @FXML private TableColumn TabColClient;
    
    @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> TabColCodeClt;
    @FXML private TableColumn<ChequeCltGestionListe ,String> TabColTypeClt;
    @FXML private TableColumn<ChequeCltGestionListe ,String> TabColNomClt;
    @FXML private TableColumn<ChequeCltGestionListe ,String> TabColPrenomClt;
    @FXML private TableColumn<ChequeCltGestionListe ,String> TabColIdFacture;
    @FXML private TableColumn<ChequeCltGestionListe ,String> TabColEtat;
    @FXML private TableColumn<ChequeCltGestionListe ,Boolean> TabColDetail;
 
    @FXML private TextField TextFieldNumeroCheque ;
    @FXML private TextField TextFieldBanque ;
    @FXML private TextField TextFieldCodeClt ;
    @FXML private TextField TextFieldCINClt ;
    @FXML private TextField TextFieldNomClt ;
    @FXML private TextField TextFieldPrenomClt;
    @FXML private TextField TextFieldIdFacture ;
    
    @FXML private DatePicker DatePickerCheque ;
    
    @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 ;
    
    private Service<Void> ThreadSearchChequeCltGestion;
            
    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;
    
    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        
        NbrLigne.setItems(cursors);
        NbrLigne.getSelectionModel().selectFirst();
        
        TabColChequeClt.setStyle( "-fx-alignment: CENTER; -fx-font-weight:bold; -fx-font-size: 10pt; -fx-border-color: #4DAE4D;");
        TabColChequeClt.getStyleClass().add("Center");
        
        TabColClient.setStyle( "-fx-alignment: CENTER; -fx-font-weight:bold; -fx-font-size: 10pt; -fx-border-color:#428BCA;");
        TabColClient.getStyleClass().add("Center");
        
        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");
        
        TabColCodeClt.setCellValueFactory(new PropertyValueFactory<ChequeCltGestionListe, String>("CodeClt"));
        TabColCodeClt.setStyle( "-fx-alignment: CENTER; -fx-font-weight:bold; -fx-font-size: 10pt; ");
        TabColCodeClt.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");
        
        TabColIdFacture.setCellValueFactory(new PropertyValueFactory<ChequeCltGestionListe, String>("IdFacture"));
        TabColIdFacture.setStyle( "-fx-alignment: CENTER; -fx-font-weight:bold; -fx-font-size: 10pt;");
        TabColIdFacture.getStyleClass().add("Center");
        
        TabColEtat.setCellValueFactory(new PropertyValueFactory<ChequeCltGestionListe, String>("Etat"));
        TabColEtat.setStyle( "-fx-alignment: CENTER; -fx-font-weight:bold; -fx-font-size: 10pt;");
        TabColEtat.getStyleClass().add("Center");
        
        TabColEtat.setCellFactory(new Callback<TableColumn<ChequeCltGestionListe,String>,TableCell<ChequeCltGestionListe,String>>(){        
            @Override
            public TableCell<ChequeCltGestionListe, String> call(TableColumn<ChequeCltGestionListe, String> param) {                
                TableCell<ChequeCltGestionListe, String> cell = new TableCell<ChequeCltGestionListe, String>(){
                    @Override
                    public void updateItem(String item, boolean empty) {
                        if(item!=null && item.equals("0")){
                            Text text = new Text("sans provision");
                            text.setFill(Color.web("#ff0000"));
                            text.setFont(Font.font("Arial", FontWeight.BOLD, 14));
                            setGraphic(text);
                        }else if(item!=null && item.equals("1")){
                            Text text = new Text("verser");
                            text.setFont(Font.font("Arial", FontWeight.BOLD, 14));
                            setGraphic(text);
                        }else if(item!=null && item.equals("2")){
                            Text text = new Text("contre chèque");
                            text.setFont(Font.font("Arial", FontWeight.BOLD, 14));
                            setGraphic(text);
                        }else{
                            setGraphic(null);
                        }
                    }
                };                           
                return cell;
            }
        });
        
        TabColDetail.setStyle( "-fx-alignment: CENTER;");TabColDetail.getStyleClass().add("Center");
        TabColDetail.setCellFactory(new Callback<TableColumn<ChequeCltGestionListe, Boolean>, TableCell<ChequeCltGestionListe, Boolean>>() {
            @Override 
            public TableCell<ChequeCltGestionListe, Boolean> call(TableColumn<ChequeCltGestionListe, Boolean> personBooleanTableColumn) {
                return new ButtonCell();
            }
        });
        
        ButtonSearchChequeCltGestion.setOnMouseClicked(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent me) {
                SearchChequeCltGestion();
            }
        });
        
        PaneChequeCltGestion.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent ke) {
                if (ke.getCode().equals(KeyCode.ENTER)) {
                    SearchChequeCltGestion();
                }
            }
        });
        
        SearchChequeCltGestion();
        
        GestionSearchChequeClt();
    }    
    
    @FXML
    private void ChequeCltVerserButtonAction(ActionEvent event) throws IOException {
       PaneChequeCltGestion.getChildren().clear();
       PaneChequeCltGestion.getChildren().add((Node) FXMLLoader.load(getClass().getResource("/Views/ChequeClt/ChequeCltVercer.fxml")));
    }
    
    @FXML
    private void ChequeCltProvisionButtonAction(ActionEvent event) throws IOException {
       PaneChequeCltGestion.getChildren().clear();
       PaneChequeCltGestion.getChildren().add((Node) FXMLLoader.load(getClass().getResource("/Views/ChequeClt/ChequeCltProvision.fxml")));
    }
    
    
    private class ButtonCell extends TableCell<ChequeCltGestionListe, Boolean> {
        
        final Button cellButton = new Button();
        ButtonCell(){
            cellButton.getStyleClass().add("btn-icon-primary");
            Image coffeeImage = new Image(getClass().getResourceAsStream("/Public/icon/detailbutton.png"));
            ImageView buttonGraphic = new ImageView();
            buttonGraphic.setImage(coffeeImage);
            cellButton.setGraphic(buttonGraphic);
            cellButton.setOnAction(new EventHandler<ActionEvent>(){ //Action when the button is pressed
                @Override
                public void handle(ActionEvent t) {
                    final ChequeCltGestionListe current = (ChequeCltGestionListe) ButtonCell.this.getTableView().getItems().get(ButtonCell.this.getIndex());
                    String IdChequeClt = current.getIdCheque();
                    Integer Source = current.getSource();
                    
                    final ChequeCltDetailController ChequeCltDetail = new ChequeCltDetailController();
                    ChequeCltDetail.Show();
                    ChequeCltDetail.Initialize(IdChequeClt, Source);
                    
                    ChequeCltDetail.ButtonExitChequeCltDetail.setOnAction(new EventHandler<ActionEvent>() {     //supprimer le message du suucés et reaficher les formulaires  
                        @Override
                        public void handle(ActionEvent event) {
                            ChequeCltDetail.AnchorPrincipal.setVisible(false);
                            if(ChequeCltDetail.LastEtat != null){
                                ObservableList<ChequeCltGestionListe> DataListChequeClt = ButtonCell.this.getTableView().getItems();
                                DataListChequeClt.get(ButtonCell.this.getIndex()).setEtat(ChequeCltDetail.LastEtat);
                                TableViewChequeCltGestion.setItems(DataListChequeClt);
                                
                                //actualiser la ligne
                                TabColEtat.setVisible(false);
                                TabColEtat.setVisible(true);
                            }
                        }
                    });
                }
            });
        }
        
        //Display button if the row is not empty
        @Override
        protected void updateItem(Boolean t, boolean empty) {
            if(!empty){
                setGraphic(cellButton);
            } else {
                setGraphic(null);
            }
        }
    }
    
    
    
/******************************************************************************                                                                             *
 *                                                                              *
 *        Methode last Next TableView                                           *
 * *                                                                            *
 ******************************************************************************/  
    
    private void SearchChequeCltGestion()
    {
        ProgressBarChequeCltGestion.setVisible(true);
        
        ButtonSearchChequeCltGestion.setDisable(true);
        
        ThreadSearchChequeCltGestion = new Service<Void>(){
            @Override
            protected Task<Void> createTask(){
                return new Task<Void>(){
                    @Override
                    protected Void call() throws Exception{
                        
                        position = 0;
                        
                        actuellepage = 1;
                        
                        String DateCheque = "";
                        if(DatePickerCheque.getValue() != null){
                            DateCheque = DatePickerCheque.getValue().toString();
                        }    
                        
                        ObservableList<ChequeCltGestionListe> ListChequeCltGestions = new ChequeCltDB().SearchChequeCltGestion(
                                                                                       position, 
                                                                                       nbrligne, 
                                                                                       TextFieldNumeroCheque.getText(), 
                                                                                       TextFieldBanque.getText(),
                                                                                       DateCheque,
                                                                                       TextFieldCodeClt.getText(), 
                                                                                       TextFieldCINClt.getText(),
                                                                                       TextFieldIdFacture.getText(), 
                                                                                       TextFieldNomClt.getText(), 
                                                                                       TextFieldPrenomClt.getText());
                            
                        TableViewChequeCltGestion.setItems(ListChequeCltGestions);
                        
                        totalcount = new ChequeCltDB().nbrChequeCltGestion(TextFieldNumeroCheque.getText(), 
                                                                           TextFieldBanque.getText(),
                                                                           DateCheque,
                                                                           TextFieldCodeClt.getText(), 
                                                                           TextFieldCINClt.getText(),
                                                                           TextFieldIdFacture.getText(), 
                                                                           TextFieldNomClt.getText(), 
                                                                           TextFieldPrenomClt.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;
                    }
                };
            }
	};
        
        ThreadSearchChequeCltGestion.setOnSucceeded(new EventHandler<WorkerStateEvent>(){
            @Override
            public void handle(WorkerStateEvent event){
                ProgressBarChequeCltGestion.setVisible(false);
                ButtonSearchChequeCltGestion.setDisable(false);
                LabelCount.setText(totalcount.toString());
                
            }
        });
        ThreadSearchChequeCltGestion.start();
    }
    
    
    private void NextLastSearchChequeCltGestion(Integer ParmPosition, Integer ParamNbrligne)
    {
        ProgressBarChequeCltGestion.setVisible(true);
        
        ButtonSearchChequeCltGestion.setDisable(true);
        
        ThreadSearchChequeCltGestion = new Service<Void>(){
            @Override
            protected Task<Void> createTask(){
                return new Task<Void>(){
                    @Override
                    protected Void call() throws Exception{
                        
                        String DateCheque = "";
                        if(DatePickerCheque.getValue() != null){
                            DateCheque = DatePickerCheque.getValue().toString();
                        }  
                        
                        ObservableList<ChequeCltGestionListe> ListChequeCltGestions = new ChequeCltDB().SearchChequeCltGestion(ParmPosition, ParamNbrligne, TextFieldNumeroCheque.getText(), TextFieldBanque.getText(), DateCheque, TextFieldCodeClt.getText(), TextFieldCINClt.getText(), TextFieldIdFacture.getText(), TextFieldNomClt.getText(), TextFieldPrenomClt.getText());
                        
                        TableViewChequeCltGestion.setItems(ListChequeCltGestions);
                        
                        return null;
                    }
                };
            }
	};
        
        ThreadSearchChequeCltGestion.setOnSucceeded(new EventHandler<WorkerStateEvent>(){
            @Override
            public void handle(WorkerStateEvent event){
                ProgressBarChequeCltGestion.setVisible(false);
                ButtonSearchChequeCltGestion.setDisable(false);
            }
        });
        ThreadSearchChequeCltGestion.start();
    }
  
    private void GestionSearchChequeClt()
    {
        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;
                NextLastSearchChequeCltGestion(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;
                    NextLastSearchChequeCltGestion(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;
                    NextLastSearchChequeCltGestion(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;
                    NextLastSearchChequeCltGestion(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;
                    NextLastSearchChequeCltGestion(position, nbrligne);
                    actuellepage=actuellepage-3 ;
                    ActuellePage.setText(Integer.toString(actuellepage));
                }
            }
        });

    }
    
        
}
    
    
    

