package Controllers.FactureClt;

import Models.CommandeClt.CommandeCltDB;
import Models.CommandeClt.CommandeCltListe;
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.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.Text;
import javafx.util.Callback;

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

    Logger logger = Logger.getLogger(FactureCltAjouterController.class.getName());
    
    @FXML private AnchorPane PaneFactCltAjouter ;
    
    @FXML private ProgressBar ProgressBarFactureCltCommande;
    
    @FXML private Button ButtonSearchFactureCltCommande ;
    
    @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<CommandeCltListe> TableViewGestionCommande;
    
    @FXML public TableColumn<CommandeCltListe ,String> TabColCodeCommande;
    @FXML public TableColumn<CommandeCltListe ,String> TabColModePaiement;
    @FXML public TableColumn<CommandeCltListe ,String> TabColTypeClient;
    @FXML public TableColumn<CommandeCltListe ,String> TabColCodeClient;
    @FXML public TableColumn<CommandeCltListe ,String> TabColTotalCommande;
    @FXML public TableColumn<CommandeCltListe ,String> TabColDateCreation ;
    @FXML public TableColumn<CommandeCltListe ,Boolean>TabColAction ;
    
    @FXML public TextField TextFieldCodeCommande;
    @FXML public TextField TextFieldCodeClient;
    @FXML public TextField TextFieldNameClient;
    @FXML public TextField TextFieldCodeDevis;
    @FXML public DatePicker DatePickerCreation;
    @FXML public RadioButton RadioComptant;
    @FXML public RadioButton RadioFacilite;
    
    private Service<Void> ThreadSearchFactureCltCommande;
    
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        //comboboxnombre des lignes tableview
        NbrLigne.setItems(cursors);
        NbrLigne.getSelectionModel().selectFirst();
        
        TableViewGestionCommande.setEditable(true);
        
        TabColCodeCommande.setStyle( "-fx-alignment: CENTER;");TabColCodeCommande.getStyleClass().add("Center");
        TabColCodeCommande.setCellValueFactory(new PropertyValueFactory<CommandeCltListe, String>("CodeCommande"));
        
        TabColTypeClient.setStyle( "-fx-alignment: CENTER;");TabColTypeClient.getStyleClass().add("Center");
        TabColTypeClient.setCellValueFactory(new PropertyValueFactory<CommandeCltListe, String>("TypeClient"));
        
        TabColCodeClient.setStyle( "-fx-alignment: CENTER;");TabColCodeClient.getStyleClass().add("Center");
        TabColCodeClient.setCellValueFactory(new PropertyValueFactory<CommandeCltListe, String>("CodeClient"));
        
        TabColModePaiement.setStyle( "-fx-alignment: CENTER;");TabColModePaiement.getStyleClass().add("Center");
        TabColModePaiement.setCellValueFactory(new PropertyValueFactory<CommandeCltListe, String>("ModePaiement"));
        
        TabColTotalCommande.setStyle( "-fx-alignment: CENTER;");TabColTotalCommande.getStyleClass().add("Center");
        TabColTotalCommande.setCellValueFactory(new PropertyValueFactory<CommandeCltListe, String>("TotalCommande"));
        
        TabColDateCreation.setStyle( "-fx-alignment: CENTER;");TabColDateCreation.getStyleClass().add("Center");
        TabColDateCreation.setCellValueFactory(new PropertyValueFactory<CommandeCltListe, String>("DateCreation"));
        
        TabColAction.setSortable(true);
        TabColAction.setStyle( "-fx-alignment: CENTER;");TabColAction.getStyleClass().add("Center");
        TabColAction.setCellFactory(new Callback<TableColumn<CommandeCltListe, Boolean>, TableCell<CommandeCltListe, Boolean>>() {
            @Override 
            public TableCell<CommandeCltListe, Boolean> call(TableColumn<CommandeCltListe, Boolean> personBooleanTableColumn) {
                return new ButtonCell();
            }
        });
        
        ButtonSearchFactureCltCommande.setOnMouseClicked(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent me) {
                SearchFactureCltCommande();
            }
        });
        
        PaneFactCltAjouter.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent ke) {
                if (ke.getCode().equals(KeyCode.ENTER)) {
                    SearchFactureCltCommande();
                }
            }
        });
        
        RadioComptant.setOnMouseClicked(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent me) {
                SearchFactureCltCommande();
            }
        });
        
        RadioFacilite.setOnMouseClicked(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent me) {
                SearchFactureCltCommande();
            }
        });
        
        GestionSearchFactureCltCommande();
        
    }   
    
    
       
    
    //Define the button cell
    private class ButtonCell extends TableCell<CommandeCltListe, 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) {
                    try {
                        // get Selected Item
                        CommandeCltListe current = (CommandeCltListe) ButtonCell.this.getTableView().getItems().get(ButtonCell.this.getIndex());
                        String codeCommande = current.getCodeCommande();
                        
                        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/Views/FactureClt/FactureCltAjouterDetailSelect.fxml"));
                        Parent NodeDetailSelect = (Parent)fxmlLoader.load();
                        FactureCltAjouterDetailSelectController FactureCltAjouterDetailSelect = fxmlLoader.getController();
                        FactureCltAjouterDetailSelect.setDataCommande(codeCommande);
                        PaneFactCltAjouter.getChildren().clear();
                        PaneFactCltAjouter.getChildren().add(NodeDetailSelect);
                    } catch (IOException ex) {
                        logger.error("FactureCltAjouterController  : FactureCltAjouterDetailSelect.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 SearchFactureCltCommande()
    {
        ProgressBarFactureCltCommande.setVisible(true);
        
        ButtonSearchFactureCltCommande.setDisable(true);
        
        ThreadSearchFactureCltCommande = 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<CommandeCltListe> ListFactureCltCommandes = new CommandeCltDB().SearchCommande(
                                                                                        position, 
                                                                                        nbrligne, 
                                                                                        TypeRegement, 
                                                                                        TextFieldCodeCommande.getText(),  
                                                                                        TextFieldCodeClient.getText(), 
                                                                                        TextFieldNameClient.getText(), 
                                                                                        TextFieldCodeDevis.getText(),
                                                                                        DateCreation);
                            
                        TableViewGestionCommande.setItems(ListFactureCltCommandes);
                        
                        totalcount = new CommandeCltDB().nbrSearchCommande(TypeRegement, TextFieldCodeCommande.getText(),  TextFieldCodeClient.getText(), TextFieldNameClient.getText(), TextFieldCodeDevis.getText(), DateCreation);
                        
                        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;
                    }
                };
            }
	};
        
        ThreadSearchFactureCltCommande.setOnSucceeded(new EventHandler<WorkerStateEvent>(){
            @Override
            public void handle(WorkerStateEvent event){
                ProgressBarFactureCltCommande.setVisible(false);
                ButtonSearchFactureCltCommande.setDisable(false);
                LabelCount.setText(totalcount.toString());
                
            }
        });
        ThreadSearchFactureCltCommande.start();
    }
    
    
    private void NextLastSearchFactureCltCommande(Integer ParmPosition, Integer ParamNbrligne)
    {
        ProgressBarFactureCltCommande.setVisible(true);
        
        ButtonSearchFactureCltCommande.setDisable(true);
        
        ThreadSearchFactureCltCommande = 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<CommandeCltListe> ListFactureCltCommandes = new CommandeCltDB().SearchCommande(ParmPosition, ParamNbrligne, TypeRegement, TextFieldCodeCommande.getText(),  TextFieldCodeClient.getText(), TextFieldNameClient.getText(), TextFieldCodeDevis.getText(), DateCreation);
                        
                        TableViewGestionCommande.setItems(ListFactureCltCommandes);
                        
                        return null;
                    }
                };
            }
	};
        
        ThreadSearchFactureCltCommande.setOnSucceeded(new EventHandler<WorkerStateEvent>(){
            @Override
            public void handle(WorkerStateEvent event){
                ProgressBarFactureCltCommande.setVisible(false);
                ButtonSearchFactureCltCommande.setDisable(false);
            }
        });
        ThreadSearchFactureCltCommande.start();
    }
  
    private void GestionSearchFactureCltCommande()
    {
        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;
                NextLastSearchFactureCltCommande(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;
                    NextLastSearchFactureCltCommande(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;
                    NextLastSearchFactureCltCommande(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;
                    NextLastSearchFactureCltCommande(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;
                    NextLastSearchFactureCltCommande(position, nbrligne);
                    actuellepage=actuellepage-3 ;
                    ActuellePage.setText(Integer.toString(actuellepage));
                }
            }
        });

    }
    
}
