package Controllers.Client;

import Models.Client.ClientEntrepriseDB;
import javafx.scene.control.ProgressBar;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import org.apache.log4j.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.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 GestionClientEntrepriseController implements Initializable {
    
    Logger logger = Logger.getLogger(GestionClientEntrepriseController.class.getName());
    
    @FXML private AnchorPane AnchorPaneGestionClt;
    
    @FXML private ProgressBar ProgressBarClientEntreprise;
    
    @FXML private Button ButtonSearchClientEntreprise;
    
    @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 GestionClientCodeEtr;
    @FXML private TextField GestionClientNomEtr;       
    @FXML private TextField GestionClientGerantEtr;
    @FXML private TextField GestionClientMatriculeEtr;
    @FXML private TextField GestionClientAdresseEtr;       
    @FXML private TextField GestionClientTelephoneEtr;
    
    @FXML private TableView<ListeClientEntreprise> TableViewListeClientEntreprise ;
    
    @FXML private TableColumn<ListeClientEntreprise ,String> CodeClientEtr;
    @FXML private TableColumn<ListeClientEntreprise ,String> NomEntreprise;
    @FXML private TableColumn<ListeClientEntreprise ,String> Gerant ;
    @FXML private TableColumn<ListeClientEntreprise ,String> matricule;
    @FXML private TableColumn<ListeClientEntreprise ,String> Adresse;
    @FXML private TableColumn<ListeClientEntreprise ,Integer> Telephone;
    @FXML private TableColumn<ListeClientEntreprise, 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> ThreadSearchClientEntreprise;
    
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        
        NbrLigne.setItems(cursors);
        NbrLigne.getSelectionModel().selectFirst();
        
        CodeClientEtr.setCellValueFactory(new PropertyValueFactory<ListeClientEntreprise, String>("code"));
        NomEntreprise.setCellValueFactory(new PropertyValueFactory<ListeClientEntreprise, String>("NomEntreprise"));
        Gerant.setCellValueFactory(new PropertyValueFactory<ListeClientEntreprise, String>("Gerant"));
        matricule.setCellValueFactory(new PropertyValueFactory<ListeClientEntreprise, String>("matricule"));
        Adresse.setCellValueFactory(new PropertyValueFactory<ListeClientEntreprise, String>("Adresse"));
        Telephone.setCellValueFactory(new PropertyValueFactory<ListeClientEntreprise, Integer>("Telephone"));
        
        Action.setSortable(true);
        Action.setStyle( "-fx-alignment: CENTER;");Action.getStyleClass().add("Center"); 
        Action.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ListeClientEntreprise, Boolean>,ObservableValue<Boolean>>() {
            @Override
            public ObservableValue<Boolean> call(TableColumn.CellDataFeatures<ListeClientEntreprise, 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<ListeClientEntreprise, Boolean>, TableCell<ListeClientEntreprise, Boolean>>() {
          @Override 
          public TableCell<ListeClientEntreprise, Boolean> call(TableColumn<ListeClientEntreprise, Boolean> personBooleanTableColumn) {
            return new ButtonCell();
          }
        });
        
        
        //DOUBLE CLIQUE SUR UN CLIENT
        TableViewListeClientEntreprise.setOnMouseClicked(new EventHandler<javafx.scene.input.MouseEvent>(){
            public void handle(MouseEvent event){
                if(event.getClickCount()>1){
                    if(TableViewListeClientEntreprise.getSelectionModel().getSelectedIndex()>=0){
                        
                        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.setDataEntreprise(TableViewListeClientEntreprise.getSelectionModel().getSelectedItem().getCode());
                            AnchorPaneGestionClt.getChildren().add(root);
                            //
                            //DcltCtl.setUser("sqdfqsdf");
                        } catch (IOException ex) {
                            logger.error("GestionClientEntrepriseController  : DetailClient.fxml :" + ex.getMessage());
                        }
                        
       
                    }
                }
                
            }
        });
        
        
        ButtonSearchClientEntreprise.setOnMouseClicked(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent me) {
                SearchClientEntreprise();
            }
        });
        
        AnchorPaneGestionClt.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent ke) {
                if (ke.getCode().equals(KeyCode.ENTER)) {
                    SearchClientEntreprise();
                }
            }
        });
        
        SearchClientEntreprise();
        
        GestionSearchClientEntreprise();
        
    }
    
    @FXML
    public void AjouterClientPersonneRadioAction(ActionEvent event) throws IOException {
        AnchorPaneGestionClt.getChildren().clear();
        AnchorPaneGestionClt.getChildren().add((Node) FXMLLoader.load(getClass().getResource("/Views/Client/GestionClientPersonne.fxml")));
    }
    
    
    //Define the button cell
    private class ButtonCell extends TableCell<ListeClientEntreprise, 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
                ListeClientEntreprise currentEntreprise = (ListeClientEntreprise) 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.setDataEntreprise(currentEntreprise.getCode());
                    
                    AnchorPaneGestionClt.getChildren().add(root);
                    } catch (IOException ex) {
                        logger.error("GestionClientEntrepriseController  : ButtonCell : DetailClient.fxml : " + ex.getMessage());
                    }
                }
            });
        }

        //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 SearchClientEntreprise()
    {
        ProgressBarClientEntreprise.setVisible(true);
        
        ButtonSearchClientEntreprise.setDisable(true);
        
        ThreadSearchClientEntreprise = new Service<Void>(){
            @Override
            protected Task<Void> createTask(){
                return new Task<Void>(){
                    @Override
                    protected Void call() throws Exception{
                        
                        position = 0;
                        
                        actuellepage = 1;
                        
                        ObservableList<ListeClientEntreprise> ListeCltEntreprise = new ClientEntrepriseDB().SearchCltEntrepriseGestion(
                                                                                        position, 
                                                                                        nbrligne, 
                                                                                        GestionClientCodeEtr.getText(), 
                                                                                        GestionClientNomEtr.getText(),  
                                                                                        GestionClientGerantEtr.getText(), 
                                                                                        GestionClientMatriculeEtr.getText(),
                                                                                        GestionClientAdresseEtr.getText(),
                                                                                        GestionClientTelephoneEtr.getText());
                            
                        TableViewListeClientEntreprise.setItems(ListeCltEntreprise);
                        
                        totalcount = new ClientEntrepriseDB().nbrCltEntrepriseGestion(GestionClientCodeEtr.getText(), GestionClientNomEtr.getText(), GestionClientGerantEtr.getText(), GestionClientMatriculeEtr.getText(), GestionClientAdresseEtr.getText(), GestionClientTelephoneEtr.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;
                    }
                };
            }
	};
        
        ThreadSearchClientEntreprise.setOnSucceeded(new EventHandler<WorkerStateEvent>(){
            @Override
            public void handle(WorkerStateEvent event){
                ProgressBarClientEntreprise.setVisible(false);
                ButtonSearchClientEntreprise.setDisable(false);
                LabelCount.setText(totalcount.toString());
                
            }
        });
        ThreadSearchClientEntreprise.start();
    }
    
    
    
    private void NextLastSearchClientEntreprise(Integer ParmPosition, Integer ParamNbrligne)
    {
        ProgressBarClientEntreprise.setVisible(true);
        
        ButtonSearchClientEntreprise.setDisable(true);
        
        ThreadSearchClientEntreprise = new Service<Void>(){
            @Override
            protected Task<Void> createTask(){
                return new Task<Void>(){
                    @Override
                    protected Void call() throws Exception{
                        
                        ObservableList<ListeClientEntreprise> ListeCltEntreprise = new ClientEntrepriseDB().SearchCltEntrepriseGestion(
                                                                                        ParmPosition, 
                                                                                        ParamNbrligne, 
                                                                                        GestionClientCodeEtr.getText(), 
                                                                                        GestionClientNomEtr.getText(),  
                                                                                        GestionClientGerantEtr.getText(), 
                                                                                        GestionClientMatriculeEtr.getText(),
                                                                                        GestionClientAdresseEtr.getText(),
                                                                                        GestionClientTelephoneEtr.getText());
                            
                        TableViewListeClientEntreprise.setItems(ListeCltEntreprise);
                        
                        
                        return null;
                    }
                };
            }
	};
        
        ThreadSearchClientEntreprise.setOnSucceeded(new EventHandler<WorkerStateEvent>(){
            @Override
            public void handle(WorkerStateEvent event){
                ProgressBarClientEntreprise.setVisible(false);
                ButtonSearchClientEntreprise.setDisable(false);
            }
        });
        ThreadSearchClientEntreprise.start();
    }
  
    private void GestionSearchClientEntreprise()
    {
        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;
                NextLastSearchClientEntreprise(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;
                    NextLastSearchClientEntreprise(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;
                    NextLastSearchClientEntreprise(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;
                    NextLastSearchClientEntreprise(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;
                    NextLastSearchClientEntreprise(position, nbrligne);
                    actuellepage=actuellepage-3 ;
                    ActuellePage.setText(Integer.toString(actuellepage));
                }
            }
        });

    }

  
}