package Controllers.TraiteClt;

import Models.TraiteClt.TraiteCltGestionDB;
import Models.TraiteClt.TraiteCltGestionListe;
import com.gluonhq.charm.glisten.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 TraiteCltGestionController implements Initializable {

    @FXML public AnchorPane PaneTraiteCltGestion ;
    
    @FXML private ProgressBar ProgressBarTraiteClt;
    
    @FXML private Button ButtonSearchTraiteClt ;
    
    @FXML public TextField TextFieldIdTraite ;
    @FXML public TextField TextFieldCodeFacture ;
    @FXML public TextField TextFieldCodeClt ;
    @FXML public TextField TextFieldNomCompet ;
    @FXML public TextField TextFieldCinClt ;
    
    @FXML public DatePicker PickerDateTraite;
    
    @FXML public TableView<TraiteCltGestionListe> TableViewTraiteCltGestion;
    
    @FXML public TableColumn<TraiteCltGestionListe ,String> TabColNumTraite;
    @FXML public TableColumn<TraiteCltGestionListe ,String> TabColEtat;
    @FXML public TableColumn<TraiteCltGestionListe ,String> TabColFacture;
    @FXML public TableColumn<TraiteCltGestionListe ,String> TabColCodeClt;
    @FXML public TableColumn<TraiteCltGestionListe ,String> TabColTypeClient;
    @FXML public TableColumn<TraiteCltGestionListe ,String> TabColNomPrenom;
    @FXML public TableColumn<TraiteCltGestionListe ,String> TabColDateTraite; 
    @FXML public TableColumn<TraiteCltGestionListe ,String> TabColDatePayer; //la date de payer par le client
    @FXML public TableColumn<TraiteCltGestionListe ,Boolean>TabColDetail;
    
    @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> ThreadSearchTraiteClt;
    
    
    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        
        NbrLigne.setItems(cursors);
        NbrLigne.getSelectionModel().selectFirst();
        
        TabColNumTraite.setCellValueFactory(new PropertyValueFactory<TraiteCltGestionListe, String>("NumTraite"));
        
        
        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"));
        
        TabColTypeClient.setStyle( "-fx-alignment: CENTER;");TabColTypeClient.getStyleClass().add("Center");
        TabColTypeClient.setCellValueFactory(new PropertyValueFactory<TraiteCltGestionListe, String>("TypeClient"));
        
        TabColNomPrenom.setCellValueFactory(new PropertyValueFactory<TraiteCltGestionListe, String>("NomPrenom"));
        
        TabColDateTraite.setStyle( "-fx-alignment: CENTER;");TabColDateTraite.getStyleClass().add("Center");
        TabColDateTraite.setCellValueFactory(new PropertyValueFactory<TraiteCltGestionListe, String>("DateTraite"));
        
        TabColDatePayer.setStyle( "-fx-alignment: CENTER;");TabColDatePayer.getStyleClass().add("Center");
        TabColDatePayer.setCellValueFactory(new PropertyValueFactory<TraiteCltGestionListe, String>("DatePayer"));
        
        TabColEtat.setStyle( "-fx-alignment: CENTER;");TabColEtat.getStyleClass().add("Center");
        TabColEtat.setCellValueFactory(new PropertyValueFactory<TraiteCltGestionListe, String>("Etat"));
        TabColEtat.setCellFactory(new Callback<TableColumn<TraiteCltGestionListe,String>,TableCell<TraiteCltGestionListe,String>>(){        
            @Override
            public TableCell<TraiteCltGestionListe, String> call(TableColumn<TraiteCltGestionListe, String> param) {                
                TableCell<TraiteCltGestionListe, String> cell = new TableCell<TraiteCltGestionListe, String>(){
                    @Override
                    public void updateItem(String item, boolean empty) {
                        //1 Payer       2 En Cours      3 En Retart
                        if(item!=null && item.equals("2")){
                            Text text = new Text("En Cours");
                            text.setFill(Color.web("#000000"));
                            text.setFont(Font.font("Arial", FontWeight.BOLD, 14));
                            setGraphic(text);
                        }else if(item!=null && item.equals("1")){
                            Text text = new Text("Payer");
                            text.setFill(Color.web("#428BCA"));
                            text.setFont(Font.font("Arial", FontWeight.BOLD, 14));
                            setGraphic(text);
                        }else if(item!=null && item.equals("3")){
                            Text text = new Text("En Retart");
                            text.setFill(Color.RED);
                            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<TraiteCltGestionListe, Boolean>, TableCell<TraiteCltGestionListe, Boolean>>() {
            @Override 
            public TableCell<TraiteCltGestionListe, Boolean> call(TableColumn<TraiteCltGestionListe, Boolean> personBooleanTableColumn) {
                return new ButtonCell();
            }
        });
        
        ButtonSearchTraiteClt.setOnMouseClicked(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent me) {
                SearchTraiteClt();
            }
        });
        
        PaneTraiteCltGestion.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent ke) {
                if (ke.getCode().equals(KeyCode.ENTER)) {
                    SearchTraiteClt();
                }
            }
        });
        
        GestionSearchTraiteClt();
    }
    
    private class ButtonCell extends TableCell<TraiteCltGestionListe, Boolean> {
        
        final Button cellButton = new Button();
        ButtonCell(){
            cellButton.getStyleClass().add("btn-icon-primary");
            Image coffeeImage = new Image(getClass().getResourceAsStream("/Public/icon/iconedit.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) {
                    
                    TraiteCltGestionListe current = (TraiteCltGestionListe) ButtonCell.this.getTableView().getItems().get(ButtonCell.this.getIndex());
                    String IdTraite = current.getNumTraite();

                    TraiteCltDetailController TraiteCltDetail =  new TraiteCltDetailController();
                    PaneTraiteCltGestion.getChildren().add(TraiteCltDetail.GetNodeTraiteCltDetail());

                    TraiteCltDetail.SetTraiteCltDetail(IdTraite);
                }
            });
        }
        
        //Display button if the row is not empty
        @Override
        protected void updateItem(Boolean t, boolean empty) {
            if(!empty){
                setGraphic(cellButton);
            } else {
                setGraphic(null);
            }
        }
    }    
    
    @FXML
    private void TraiteCltRetardButtonAction(ActionEvent event) throws IOException {
       PaneTraiteCltGestion.getChildren().clear();
       PaneTraiteCltGestion.getChildren().add((Node) FXMLLoader.load(getClass().getResource("/Views/TraiteClt/TraiteCltRetard.fxml")));
    }
       
    
/******************************************************************************                                                                             *
 *                                                                              *
 *        Methode last Next TableView                                           *
 * *                                                                            *
 ******************************************************************************/  
    
    private void SearchTraiteClt()
    {
        ProgressBarTraiteClt.setVisible(true);
        
        ButtonSearchTraiteClt.setDisable(true);
        
        ThreadSearchTraiteClt = new Service<Void>(){
            @Override
            protected Task<Void> createTask(){
                return new Task<Void>(){
                    @Override
                    protected Void call() throws Exception{
                        
                        position = 0;
                        
                        actuellepage = 1;
                        
                        String DateTraite = "";
                        if(PickerDateTraite.getValue() != null){
                            DateTraite = PickerDateTraite.getValue().toString();
                        }    
                        
                        ObservableList<TraiteCltGestionListe> ListTraiteClts = new TraiteCltGestionDB().SearchTraiteClt(
                                                                                        position, 
                                                                                        nbrligne, 
                                                                                        TextFieldIdTraite.getText(), 
                                                                                        TextFieldCodeFacture.getText(),  
                                                                                        DateTraite, 
                                                                                        TextFieldCodeClt.getText(), 
                                                                                        TextFieldCinClt.getText(),
                                                                                        TextFieldNomCompet.getText());
                            
                        TableViewTraiteCltGestion.setItems(ListTraiteClts);
                        
                        totalcount = new TraiteCltGestionDB().nbrSearchTraiteClt(TextFieldIdTraite.getText(), 
                                                                                        TextFieldCodeFacture.getText(),  
                                                                                        DateTraite, 
                                                                                        TextFieldCodeClt.getText(), 
                                                                                        TextFieldCinClt.getText(),
                                                                                        TextFieldNomCompet.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;
                    }
                };
            }
	};
        
        ThreadSearchTraiteClt.setOnSucceeded(new EventHandler<WorkerStateEvent>(){
            @Override
            public void handle(WorkerStateEvent event){
                ProgressBarTraiteClt.setVisible(false);
                ButtonSearchTraiteClt.setDisable(false);
                LabelCount.setText(totalcount.toString());
                
            }
        });
        ThreadSearchTraiteClt.start();
    }
    
    
    private void NextLastSearchTraiteClt(Integer ParmPosition, Integer ParamNbrligne)
    {
        ProgressBarTraiteClt.setVisible(true);
        
        ButtonSearchTraiteClt.setDisable(true);
        
        ThreadSearchTraiteClt = new Service<Void>(){
            @Override
            protected Task<Void> createTask(){
                return new Task<Void>(){
                    @Override
                    protected Void call() throws Exception{
                        
                        String DateTraite = "";
                        if(PickerDateTraite.getValue() != null){
                            DateTraite = PickerDateTraite.getValue().toString();
                        } 
                        
                        ObservableList<TraiteCltGestionListe> ListTraiteClts = new TraiteCltGestionDB().SearchTraiteClt(
                                                                                        ParmPosition, 
                                                                                        ParamNbrligne,
                                                                                        TextFieldIdTraite.getText(), 
                                                                                        TextFieldCodeFacture.getText(),  
                                                                                        DateTraite, 
                                                                                        TextFieldCodeClt.getText(), 
                                                                                        TextFieldCinClt.getText(),
                                                                                        TextFieldNomCompet.getText());
                        
                        TableViewTraiteCltGestion.setItems(ListTraiteClts);
                        
                        return null;
                    }
                };
            }
	};
        
        ThreadSearchTraiteClt.setOnSucceeded(new EventHandler<WorkerStateEvent>(){
            @Override
            public void handle(WorkerStateEvent event){
                ProgressBarTraiteClt.setVisible(false);
                ButtonSearchTraiteClt.setDisable(false);
            }
        });
        ThreadSearchTraiteClt.start();
    }
  
    private void GestionSearchTraiteClt()
    {
        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;
                NextLastSearchTraiteClt(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;
                    NextLastSearchTraiteClt(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;
                    NextLastSearchTraiteClt(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;
                    NextLastSearchTraiteClt(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;
                    NextLastSearchTraiteClt(position, nbrligne);
                    actuellepage=actuellepage-3 ;
                    ActuellePage.setText(Integer.toString(actuellepage));
                }
            }
        });

    }
}
