package Controllers.Client;

import Models.Client.ClientDB;
import com.gluonhq.charm.glisten.control.ProgressBar;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.beans.property.SimpleBooleanProperty;
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.Parent;
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.text.Text;
import javafx.util.Callback;

/**
 * FXML Controller class
 * @author Maher Ben Tili
 */
public class GestionClientPersonneController implements Initializable {
    
    @FXML private AnchorPane AnchorPaneGestionClt;
    
    @FXML private AnchorPane AnchorPaneCltBody ;
    
    @FXML private ProgressBar ProgressBarClientPersonne;
    
    @FXML private Button ButtonSearchClientPersonne;
    
    @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 ;

    @FXML private TextField GestionClientcode; 
    @FXML private TextField GestionClientcin;
    @FXML private TextField GestionClientnomcomplet;
    @FXML private TextField GestionClientnom;
    @FXML private TextField GestionClientprenom;
    @FXML private DatePicker DatePickerNaissance;
    
    @FXML private TableView<ListeClient> TableViewListeClient ;
    
    @FXML private TableColumn<ListeClient ,Integer> codeclient;
    @FXML private TableColumn<ListeClient ,Integer> cin;
    @FXML private TableColumn<ListeClient ,String> nomcomplet;
    @FXML private TableColumn<ListeClient ,String> nom;
    @FXML private TableColumn<ListeClient ,String> prenom;
    @FXML private TableColumn<ListeClient ,Integer> tele;
    @FXML private TableColumn<ListeClient, Boolean> Action ;
    
    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> ThreadSearchClientPersonne;
    
    
    
    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        
        NbrLigne.setItems(cursors);
        NbrLigne.getSelectionModel().selectFirst();
        
        codeclient.setCellValueFactory(new PropertyValueFactory<ListeClient, Integer>("code"));
        
        cin.setCellValueFactory(new PropertyValueFactory<ListeClient, Integer>("cin"));
        
        nomcomplet.setCellValueFactory(new PropertyValueFactory<ListeClient, String>("nomcomplet"));
        
        nom.setCellValueFactory(new PropertyValueFactory<ListeClient, String>("nom"));
        
        prenom.setCellValueFactory(new PropertyValueFactory<ListeClient, String>("prenom"));
        
        tele.setCellValueFactory(new PropertyValueFactory<ListeClient, Integer>("tele"));
        
        Action.setSortable(true);
        Action.setStyle( "-fx-alignment: CENTER;");Action.getStyleClass().add("Center"); 
        Action.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ListeClient, Boolean>, ObservableValue<Boolean>>() {
            @Override
            public ObservableValue<Boolean> call(TableColumn.CellDataFeatures<ListeClient, Boolean> p) {
                return new SimpleBooleanProperty(p.getValue() != null);
            }
        });
 
        // create a cell value factory with an add button for each row in the table.
        Action.setCellFactory(new Callback<TableColumn<ListeClient, Boolean>, TableCell<ListeClient, Boolean>>() {
          @Override 
          public TableCell<ListeClient, Boolean> call(TableColumn<ListeClient, Boolean> personBooleanTableColumn) {
            return new GestionClientPersonneController.ButtonCell();
          }
        });
        
        ButtonSearchClientPersonne.setOnMouseClicked(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent me) {
                SearchClientPersonne();
            }
        });
        
        AnchorPaneGestionClt.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent ke) {
                if (ke.getCode().equals(KeyCode.ENTER)) {
                    SearchClientPersonne();
                }
            }
        });
        
        
        GestionSearchClientPersonne();
    }    
    
    
    
    //Define the button cell
    private class ButtonCell extends TableCell<ListeClient, 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);
        
        //Action when the button is pressed
        cellButton.setOnAction(new EventHandler<ActionEvent>(){
            @Override
            public void handle(ActionEvent t) {
                // get Selected Item
                ListeClient currentPerson = (ListeClient) ButtonCell.this.getTableView().getItems().get(ButtonCell.this.getIndex());
                try {
                    AnchorPaneGestionClt.getChildren().clear();
                    FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/Views/Client/DetailClient.fxml"));
                    Parent root = (Parent)fxmlLoader.load();
                    DetailClientController DcltCtl = fxmlLoader.<DetailClientController>getController();
                    DcltCtl.setDataClient(currentPerson.getCode().toString());
                    AnchorPaneGestionClt.getChildren().add(root);
                    } catch (IOException ex) {
                        Logger.getLogger(GestionClientEntrepriseController.class.getName()).log(Level.SEVERE, null, ex);
                    }
               
                }
            });
        }

        //Display button if the row is not empty
        @Override
        protected void updateItem(Boolean t, boolean empty) {
            if(!empty){
                setGraphic(cellButton);
            } else {
                setGraphic(null);
            }
        }
    }
    
    // modifer pour client entreprise
    @FXML
    public void AjouterClientEntrepriseRadioAction(ActionEvent event) throws IOException {
        AnchorPaneGestionClt.getChildren().clear();
        AnchorPaneGestionClt.getChildren().add((Node) FXMLLoader.load(getClass().getResource("/Views/Client/GestionClientEntreprise.fxml")));
    }
    
    
    
/******************************************************************************                                                                             *
 *                                                                              *
 *                       Methode last Next TableView                            *
 * *                                                                            *
 ******************************************************************************/  
 
    private void SearchClientPersonne()
    {
        ProgressBarClientPersonne.setVisible(true);
        
        ButtonSearchClientPersonne.setDisable(true);
        
        ThreadSearchClientPersonne = new Service<Void>(){
            @Override
            protected Task<Void> createTask(){
                return new Task<Void>(){
                    @Override
                    protected Void call() throws Exception{
                        
                        position = 0;
                        
                        actuellepage = 1;
                        
                        String DateNaissance = "";
                        if(DatePickerNaissance.getValue() != null){
                            DateNaissance = DatePickerNaissance.getValue().toString();
                        }    
                        
                        ObservableList<ListeClient> ListeCltPersonne = new ClientDB().SearchCltPersonneGestion(
                                                                                        position, 
                                                                                        nbrligne, 
                                                                                        GestionClientcode.getText(), 
                                                                                        GestionClientcin.getText(),  
                                                                                        GestionClientnomcomplet.getText(), 
                                                                                        GestionClientnom.getText(),
                                                                                        GestionClientprenom.getText(),
                                                                                        DateNaissance);
                            
                        TableViewListeClient.setItems(ListeCltPersonne);
                        
                        totalcount = new ClientDB().nbrCltPersonneGestion(GestionClientcode.getText(), GestionClientcin.getText(), GestionClientnomcomplet.getText(), GestionClientnom.getText(), GestionClientprenom.getText(), DateNaissance);
                        
                        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;
                    }
                };
            }
	};
        
        ThreadSearchClientPersonne.setOnSucceeded(new EventHandler<WorkerStateEvent>(){
            @Override
            public void handle(WorkerStateEvent event){
                ProgressBarClientPersonne.setVisible(false);
                ButtonSearchClientPersonne.setDisable(false);
                LabelCount.setText(totalcount.toString());
                
            }
        });
        ThreadSearchClientPersonne.start();
    }
    
    
    
    private void NextLastSearchClientPersonne(Integer ParmPosition, Integer ParamNbrligne)
    {
        ProgressBarClientPersonne.setVisible(true);
        
        ButtonSearchClientPersonne.setDisable(true);
        
        ThreadSearchClientPersonne = new Service<Void>(){
            @Override
            protected Task<Void> createTask(){
                return new Task<Void>(){
                    @Override
                    protected Void call() throws Exception{
                        
                        String DateNaissance = "";
                        if(DatePickerNaissance.getValue() != null){
                            DateNaissance = DatePickerNaissance.getValue().toString();
                        }    
                        
                        ObservableList<ListeClient> ListeCltPersonne = new ClientDB().SearchCltPersonneGestion(
                                                                                        ParmPosition, 
                                                                                        ParamNbrligne, 
                                                                                        GestionClientcode.getText(), 
                                                                                        GestionClientcin.getText(),  
                                                                                        GestionClientnomcomplet.getText(), 
                                                                                        GestionClientnom.getText(),
                                                                                        GestionClientprenom.getText(),
                                                                                        DateNaissance);
                            
                        TableViewListeClient.setItems(ListeCltPersonne);
                        
                        
                        return null;
                    }
                };
            }
	};
        
        ThreadSearchClientPersonne.setOnSucceeded(new EventHandler<WorkerStateEvent>(){
            @Override
            public void handle(WorkerStateEvent event){
                ProgressBarClientPersonne.setVisible(false);
                ButtonSearchClientPersonne.setDisable(false);
            }
        });
        ThreadSearchClientPersonne.start();
    }
  
    private void GestionSearchClientPersonne()
    {
        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;
                NextLastSearchClientPersonne(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;
                    NextLastSearchClientPersonne(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;
                    NextLastSearchClientPersonne(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;
                    NextLastSearchClientPersonne(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;
                    NextLastSearchClientPersonne(position, nbrligne);
                    actuellepage=actuellepage-3 ;
                    ActuellePage.setText(Integer.toString(actuellepage));
                }
            }
        });

    }
    
}    
    
    
