package Controllers.DevisClt;

import Models.DevisClt.DevisCltListe;
import Models.DevisClt.DevisDB;
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.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.RadioButton;
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.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.util.Callback;

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

    Logger logger = Logger.getLogger(DevisCltGestionController.class.getName());
    
    @FXML private AnchorPane PaneDevisGestion ;
    
    @FXML private ProgressBar ProgressBarDevisClt;
    
    @FXML private Button ButtonSearchDevisClt;
    
    @FXML private AnchorPane ListerPages;
    @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;
    
    @FXML public TableView<DevisCltListe> TableViewGestionDevis;
    
    @FXML public TableColumn<DevisCltListe ,String> TabColCodeDevis;
    @FXML public TableColumn<DevisCltListe ,String> TabColModePaiement;
    @FXML public TableColumn<DevisCltListe ,String> TabColTypeClient;
    @FXML public TableColumn<DevisCltListe ,String> TabColCodeClient;
    @FXML public TableColumn<DevisCltListe ,String> TabColTotalDevis;
    @FXML public TableColumn<DevisCltListe ,String> TabColDateCreation ;
    @FXML public TableColumn<DevisCltListe ,String> TabColDateFinValidite;
    @FXML public TableColumn<DevisCltListe ,Boolean>TabColDetail ;
    
    @FXML public TextField TextFieldCodeDevis ;
    @FXML public TextField TextFieldCodeClient ;
    @FXML public TextField TextFieldNomPrenomClient ;
    @FXML public TextField TextFieldCinClient;
    @FXML public DatePicker DatePickerCreation ;
    @FXML public RadioButton RadioComptant;
    @FXML public RadioButton RadioFacilite;
    
    private Service<Void> ThreadSearchDevisClt;
    
    @FXML
    private void AddDevisButtonAction(ActionEvent event) throws IOException {
        
       //inisialiser les données de Sauvgarde des opération
       DevisAjouterController.TypeClient = 2 ;
       DevisAjouterController.codeclient = null ;
       DevisAjouterController.codecliententre = null ;
       DevisAjouterController.data.clear();
       DevisAjouterController.FinValidite = null;
       DevisAjouterController.Mode = null;
       
       PaneDevisGestion.getChildren().clear();
       PaneDevisGestion.getChildren().add((Node) FXMLLoader.load(getClass().getResource("/Views/Devis/DevisAjouter.fxml")));
    }
    
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        
        //comboboxnombre des lignes tableview
        NbrLigne.setItems(cursors);
        NbrLigne.getSelectionModel().selectFirst();
        
        TableViewGestionDevis.setEditable(true);
        
        TabColCodeDevis.setStyle( "-fx-alignment: CENTER;");TabColCodeDevis.getStyleClass().add("Center");
        TabColCodeDevis.setCellValueFactory(new PropertyValueFactory<DevisCltListe, String>("CodeDevis"));
        
        TabColTypeClient.setStyle( "-fx-alignment: CENTER;");TabColTypeClient.getStyleClass().add("Center");
        TabColTypeClient.setCellValueFactory(new PropertyValueFactory<DevisCltListe, String>("TypeClient"));
        
        TabColCodeClient.setStyle( "-fx-alignment: CENTER;");TabColCodeClient.getStyleClass().add("Center");
        TabColCodeClient.setCellValueFactory(new PropertyValueFactory<DevisCltListe, String>("CodeClient"));
        
        TabColModePaiement.setStyle( "-fx-alignment: CENTER;");TabColModePaiement.getStyleClass().add("Center");
        TabColModePaiement.setCellValueFactory(new PropertyValueFactory<DevisCltListe, String>("ModePaiement"));
        
        TabColTotalDevis.setStyle( "-fx-alignment: CENTER;");TabColTotalDevis.getStyleClass().add("Center");
        TabColTotalDevis.setCellValueFactory(new PropertyValueFactory<DevisCltListe, String>("TotalDevis"));
        
        TabColDateCreation.setStyle( "-fx-alignment: CENTER;");TabColDateCreation.getStyleClass().add("Center");
        TabColDateCreation.setCellValueFactory(new PropertyValueFactory<DevisCltListe, String>("DateCreation"));
        
        TabColDateFinValidite.setStyle( "-fx-alignment: CENTER;");TabColDateFinValidite.getStyleClass().add("Center");
        TabColDateFinValidite.setCellValueFactory(new PropertyValueFactory<DevisCltListe, String>("FinValidite"));
        
        TabColDetail.setSortable(true);
        TabColDetail.setStyle( "-fx-alignment: CENTER;");TabColDetail.getStyleClass().add("Center");
        TabColDetail.setCellFactory(new Callback<TableColumn<DevisCltListe, Boolean>, TableCell<DevisCltListe, Boolean>>() {
          @Override 
          public TableCell<DevisCltListe, Boolean> call(TableColumn<DevisCltListe, Boolean> personBooleanTableColumn) {
            return new ButtonCell();
          }
        });
        
        ButtonSearchDevisClt.setOnMouseClicked(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent me) {
                SearchDevisClt();
            }
        });
        
        PaneDevisGestion.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent ke) {
                if (ke.getCode().equals(KeyCode.ENTER)) {
                    SearchDevisClt();
                }
            }
        });
        
        SearchDevisClt();
        
        GestionSearchDevisClt();
    }
    
    
    
    //Define the button cell
    private class ButtonCell extends TableCell<DevisCltListe, 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) {
                    // get Selected Item
                    DevisCltListe current = (DevisCltListe) ButtonCell.this.getTableView().getItems().get(ButtonCell.this.getIndex());
                    String codedevis = current.getCodeDevis();
                    try {
                        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/Views/Devis/DevisDetail.fxml"));
                        Parent NodeDetail = (Parent)fxmlLoader.load();
                        DevisDetailController devisdetail =  fxmlLoader.getController();
                        devisdetail.AnchorPaneSucces.setVisible(false);
                        devisdetail.TextSucces.setText("Information Devis");
                        devisdetail.TextSucces.setLayoutX(30);
                        devisdetail.TextSucces.setFont(Font.font("Arial", FontWeight.NORMAL, 21));
                        devisdetail.TextDescSucces.setVisible(false);
                        devisdetail.SowDetailDevis(codedevis);
                        PaneDevisGestion.getChildren().add(NodeDetail);
                    } catch (IOException ex) {
                        logger.error("DevisCltGestionController  : DevisDetail.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 client  Entreprise                   *
 * *                                                                            *
 ******************************************************************************/  
 
    private void SearchDevisClt()
    {
        ProgressBarDevisClt.setVisible(true);
        
        ButtonSearchDevisClt.setDisable(true);
        
        ThreadSearchDevisClt = new Service<Void>(){
            @Override
            protected Task<Void> createTask(){
                return new Task<Void>(){
                    @Override
                    protected Void call() throws Exception{
                        
                        position = 0;
                        
                        actuellepage = 1;
                        
                        String DateCreation = "";
                        if(DatePickerCreation.getValue() != null){
                            DateCreation = DatePickerCreation.getValue().toString();
                        }    
                        
                        //     0comptant        1facilité
                        String TypeRegement = "";
                        if(RadioComptant.isSelected()){
                            TypeRegement = "0";
                        }else if(RadioFacilite.isSelected()){
                            TypeRegement = "1";
                        }
                        
                        ObservableList<DevisCltListe> ListDevisClts = new DevisDB().SearchDevisCltGestion(
                                                                                        position, 
                                                                                        nbrligne, 
                                                                                        TextFieldCodeDevis.getText(), 
                                                                                        TextFieldCodeClient.getText(),  
                                                                                        TypeRegement, 
                                                                                        DateCreation,
                                                                                        TextFieldNomPrenomClient.getText(),
                                                                                        TextFieldCinClient.getText());
                            
                        TableViewGestionDevis.setItems(ListDevisClts);
                        
                        totalcount = new DevisDB().nbrDevisCltGestion(TextFieldCodeDevis.getText(),  TextFieldCodeClient.getText(), TypeRegement,  DateCreation, TextFieldNomPrenomClient.getText(), TextFieldCinClient.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;
                    }
                };
            }
	};
        
        ThreadSearchDevisClt.setOnSucceeded(new EventHandler<WorkerStateEvent>(){
            @Override
            public void handle(WorkerStateEvent event){
                ProgressBarDevisClt.setVisible(false);
                ButtonSearchDevisClt.setDisable(false);
                LabelCount.setText(totalcount.toString());
                
            }
        });
        ThreadSearchDevisClt.start();
    }
    
    
    private void NextLastSearchDevisClt(Integer ParmPosition, Integer ParamNbrligne)
    {
        ProgressBarDevisClt.setVisible(true);
        
        ButtonSearchDevisClt.setDisable(true);
        
        ThreadSearchDevisClt = new Service<Void>(){
            @Override
            protected Task<Void> createTask(){
                return new Task<Void>(){
                    @Override
                    protected Void call() throws Exception{
                        
                        String DateCreation = "";
                        if(DatePickerCreation.getValue() != null){
                            DateCreation = DatePickerCreation.getValue().toString();
                        }    
                        
                        //     0comptant        1facilité
                        String TypeRegement = "";
                        if(RadioComptant.isSelected()){
                            TypeRegement = "0";
                        }else if(RadioFacilite.isSelected()){
                            TypeRegement = "1";
                        }
                        
                        ObservableList<DevisCltListe> ListDevisClts = new DevisDB().SearchDevisCltGestion(ParmPosition, ParamNbrligne, TextFieldCodeDevis.getText(),  TextFieldCodeClient.getText(), TypeRegement,  DateCreation, TextFieldNomPrenomClient.getText(), TextFieldCinClient.getText());
                        
                        TableViewGestionDevis.setItems(ListDevisClts);
                        
                        return null;
                    }
                };
            }
	};
        
        ThreadSearchDevisClt.setOnSucceeded(new EventHandler<WorkerStateEvent>(){
            @Override
            public void handle(WorkerStateEvent event){
                ProgressBarDevisClt.setVisible(false);
                ButtonSearchDevisClt.setDisable(false);
            }
        });
        ThreadSearchDevisClt.start();
    }
  
    private void GestionSearchDevisClt()
    {
        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;
                NextLastSearchDevisClt(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;
                    NextLastSearchDevisClt(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;
                    NextLastSearchDevisClt(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;
                    NextLastSearchDevisClt(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;
                    NextLastSearchDevisClt(position, nbrligne);
                    actuellepage=actuellepage-3 ;
                    ActuellePage.setText(Integer.toString(actuellepage));
                }
            }
        });

    }
    
}
