package Controllers.BonReceptionFrs;

import Models.BonReceptionFrs.BonReceptionGestionDB;
import Models.BonReceptionFrs.BonReceptionGestionList;
import Models.Fournisseur.FournisseurDB;
import Models.Stock.StockDB;
import javafx.scene.control.ProgressBar;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
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.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;
import org.apache.log4j.Logger;
import org.controlsfx.control.textfield.TextFields;


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

    @FXML public AnchorPane PaneBonReceptionGestion ;
    
    @FXML private ProgressBar ProgressBarBonReceptionFrs;
    
    @FXML public TableView<BonReceptionGestionList> TableViewBonReceptionGestion;
    @FXML public TableColumn<BonReceptionGestionList ,String> TabColNumero;
    @FXML public TableColumn<BonReceptionGestionList ,String> TabColFournisseur;
    @FXML public TableColumn<BonReceptionGestionList ,String> TabColDate;
    @FXML public TableColumn<BonReceptionGestionList ,String> TabColHeur;
    @FXML public TableColumn<BonReceptionGestionList ,String> TabColLocalReception;
    @FXML public TableColumn<BonReceptionGestionList ,String> TabColTransporteur;
    @FXML public TableColumn<BonReceptionGestionList ,String> TabColFacture;
    @FXML public TableColumn<BonReceptionGestionList ,Boolean> TabColDetail;
    
    @FXML public TextField  TextFieldNumero ;
    @FXML public TextField  TextFieldTransporteur ;
    @FXML public TextField  TextFieldFacture ;
    @FXML public DatePicker DatePickerDateReception;
    @FXML private TextField TextFieldFournisseur;
    @FXML public ChoiceBox ChoiceBoxLocalReception ;
    
    @FXML public AnchorPane PaneProgressBonReception;
    
    @FXML private Button ButtonSearchBonReceptionFrs;
    
    @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> ThreadSearchBonReceptionGestionFrs;
    
    public static ArrayList<String> ListFournisseur = new  ArrayList<>();
    public static ArrayList<String> ListLocale = new  ArrayList<>();
    
    String LocalReception = "";
    String IdFournisseur = "";
    
    Logger logger = Logger.getLogger(BonReceptionGestionFrsController.class.getName());
    
    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        
        NbrLigne.setItems(cursors);
        NbrLigne.getSelectionModel().selectFirst();
        
        TabColNumero.setStyle( "-fx-alignment: CENTER;");
        TabColNumero.getStyleClass().add("Center");
        TabColNumero.setCellValueFactory(new PropertyValueFactory<BonReceptionGestionList, String>("Numero"));
        
        TabColFournisseur.setStyle( "-fx-alignment: CENTER;");
        TabColFournisseur.getStyleClass().add("Center");
        TabColFournisseur.setCellValueFactory(new PropertyValueFactory<BonReceptionGestionList, String>("Fournisseur"));
        
        TabColDate.setStyle( "-fx-alignment: CENTER;");
        TabColDate.getStyleClass().add("Center");
        TabColDate.setCellValueFactory(new PropertyValueFactory<BonReceptionGestionList, String>("Date"));
        
        TabColHeur.setStyle( "-fx-alignment: CENTER;");
        TabColHeur.getStyleClass().add("Center");
        TabColHeur.setCellValueFactory(new PropertyValueFactory<BonReceptionGestionList, String>("Heur"));
        
        TabColLocalReception.setStyle( "-fx-alignment: CENTER;");
        TabColLocalReception.getStyleClass().add("Center");
        TabColLocalReception.setCellValueFactory(new PropertyValueFactory<BonReceptionGestionList, String>("LocalReception"));
        
        TabColTransporteur.setStyle( "-fx-alignment: CENTER;");
        TabColTransporteur.getStyleClass().add("Center");
        TabColTransporteur.setCellValueFactory(new PropertyValueFactory<BonReceptionGestionList, String>("Transporteur"));
        
        TabColFacture.setStyle( "-fx-alignment: CENTER;");
        TabColFacture.getStyleClass().add("Center");
        TabColFacture.setCellValueFactory(new PropertyValueFactory<BonReceptionGestionList, String>("Facture"));
        
        TabColDetail.setStyle( "-fx-alignment: CENTER;");TabColDetail.getStyleClass().add("Center");
        TabColDetail.setCellFactory(new Callback<TableColumn<BonReceptionGestionList, Boolean>, TableCell<BonReceptionGestionList, Boolean>>() {
            @Override 
            public TableCell<BonReceptionGestionList, Boolean> call(TableColumn<BonReceptionGestionList, Boolean> personBooleanTableColumn) {
                return new ButtonCell();
            }
        });
        
        setDefaultFormData();
        
        ChoiceBoxLocalReception.valueProperty().addListener(new ChangeListener<String>() {
            @Override 
            public void changed(ObservableValue ov, String t, String ValLocal) {
                LocalReception = ValLocal;
            }    
        });
        
        
        TextFieldFournisseur.textProperty().addListener(new ChangeListener<String>() { 
            @Override 
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { 
                if(newValue.contains(" - ")){
                    String[] array = newValue.split(" - ", -1);
                    IdFournisseur = array[0];
                }
            } 
        });
        
        
        ButtonSearchBonReceptionFrs.setOnMouseClicked(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent me) {
                SearchBonReceptionGestionFrs();
            }
        });
        
        PaneBonReceptionGestion.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent ke) {
                if (ke.getCode().equals(KeyCode.ENTER)) {
                    SearchBonReceptionGestionFrs();
                }
            }
        });
        
        GestionSearchBonReceptionFrs();
        
        SearchBonReceptionGestionFrs();
        
    }


    private class ButtonCell extends TableCell<BonReceptionGestionList, 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);
            cellButton.setOnAction(new EventHandler<ActionEvent>(){ //Action when the button is pressed
                @Override
                public void handle(ActionEvent t) {
                    try {
                        BonReceptionGestionList BonReceptionGestion = (BonReceptionGestionList)getTableRow().getItem();
                        
                        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/Views/BonReceptionFrs/BonReceptionDetailFrs.fxml"));
                        Parent ParentFxmlFournisseur = (Parent)fxmlLoader.load();
                        BonReceptionDetailFrsController BonReceptionDetailFrs = fxmlLoader.getController();
                        BonReceptionDetailFrs.setDataBonReceptionDetailFrs(BonReceptionGestion.getCode());
                        PaneBonReceptionGestion.getChildren().clear();
                        PaneBonReceptionGestion.getChildren().add(ParentFxmlFournisseur);
                        BonReceptionDetailFrs.setContainsDetailInformation();
                    }catch (IOException ex) {
                        logger.error(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);
            }
        }
    }
    
    
    @FXML
    private void BonReceptionAjouterFrsButtonAction(ActionEvent event) throws IOException {
       PaneBonReceptionGestion.getChildren().clear();
       PaneBonReceptionGestion.getChildren().add((Node) FXMLLoader.load(getClass().getResource("/Views/BonReceptionFrs/BonReceptionAjouterFrs.fxml")));
    }
    
   
    private void setDefaultFormData()
    {
        ProgressBarBonReceptionFrs.setVisible(true);
        
        ThreadSearchBonReceptionGestionFrs = new Service<Void>(){
            @Override
            protected Task<Void> createTask(){
                return new Task<Void>(){
                    @Override
                    protected Void call() throws Exception{
                        
                        try{
                            ListFournisseur = new FournisseurDB().getIdNomFournisseur();
                            TextFields.bindAutoCompletion(TextFieldFournisseur, ListFournisseur);

                            ListLocale = new StockDB().getAllListLocal();
                            ChoiceBoxLocalReception.getItems().addAll(ListLocale);
                        }catch (Exception ex) {
                            logger.error(ex.getMessage());
                        }
                        return null;
                    }
                };
            }
	};
        ThreadSearchBonReceptionGestionFrs.setOnSucceeded(new EventHandler<WorkerStateEvent>(){
            @Override
            public void handle(WorkerStateEvent event){
                ProgressBarBonReceptionFrs.setVisible(false);
                
            }
        });
        
        ThreadSearchBonReceptionGestionFrs.setOnFailed(new EventHandler<WorkerStateEvent>(){
            @Override
            public void handle(WorkerStateEvent event){
                logger.error(ThreadSearchBonReceptionGestionFrs.getException());
            }
        });
        
        ThreadSearchBonReceptionGestionFrs.start();
    }
    
/******************************************************************************                                                                             *
 *                                                                              *
 *                       Methode last Next TableView 		                     *
 * *                                                                            *
 ******************************************************************************/  
 
    private void SearchBonReceptionGestionFrs()
    {
        ProgressBarBonReceptionFrs.setVisible(true);
        
        ButtonSearchBonReceptionFrs.setDisable(true);
        
        ThreadSearchBonReceptionGestionFrs = new Service<Void>(){
            @Override
            protected Task<Void> createTask(){
                return new Task<Void>(){
                    @Override
                    protected Void call() throws Exception{
                        
                        position = 0;
                        
                        actuellepage = 1;
                        
                        String DateReception = "";
                        if(DatePickerDateReception.getValue() != null){
                            DateReception = DatePickerDateReception.getValue().toString();
                        }    
                        
                        
                        
                        ObservableList<BonReceptionGestionList> ListBonReceptionGestionFrs = new BonReceptionGestionDB().SearchBonReceptionGestionFrs(
                                                                                        position, 
                                                                                        nbrligne, 
                                                                                        TextFieldNumero.getText(), 
                                                                                        TextFieldTransporteur.getText(),  
                                                                                        TextFieldFacture.getText(), 
                                                                                        DateReception,
                                                                                        IdFournisseur,
                                                                                        LocalReception);
                            
                        TableViewBonReceptionGestion.setItems(ListBonReceptionGestionFrs);
                        
                        totalcount = new BonReceptionGestionDB().nbrBonReceptionGestionFrsGestion(TextFieldNumero.getText(), TextFieldTransporteur.getText(), TextFieldFacture.getText(), DateReception, IdFournisseur, LocalReception);
                        
                        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;
                    }
                };
            }
	};
        
        ThreadSearchBonReceptionGestionFrs.setOnSucceeded(new EventHandler<WorkerStateEvent>(){
            @Override
            public void handle(WorkerStateEvent event){
                ProgressBarBonReceptionFrs.setVisible(false);
                ButtonSearchBonReceptionFrs.setDisable(false);
                LabelCount.setText(totalcount.toString());
                
            }
        });
        ThreadSearchBonReceptionGestionFrs.start();
    }
    
    
    private void NextLastSearchBonReceptionGestionFrs(Integer ParmPosition, Integer ParamNbrligne)
    {
        ProgressBarBonReceptionFrs.setVisible(true);
        
        ButtonSearchBonReceptionFrs.setDisable(true);
        
        ThreadSearchBonReceptionGestionFrs = new Service<Void>(){
            @Override
            protected Task<Void> createTask(){
                return new Task<Void>(){
                    @Override
                    protected Void call() throws Exception{
                        
                        String DateReception = "";
                        if(DatePickerDateReception.getValue() != null){
                            DateReception = DatePickerDateReception.getValue().toString();
                        }  
                        
                        ObservableList<BonReceptionGestionList> ListBonReceptionGestionFrss = new BonReceptionGestionDB().SearchBonReceptionGestionFrs(ParmPosition, ParamNbrligne, TextFieldNumero.getText(), TextFieldTransporteur.getText(), TextFieldFacture.getText(), DateReception, IdFournisseur, LocalReception);
                        
                        TableViewBonReceptionGestion.setItems(ListBonReceptionGestionFrss);
                        
                        return null;
                    }
                };
            }
	};
        
        ThreadSearchBonReceptionGestionFrs.setOnSucceeded(new EventHandler<WorkerStateEvent>(){
            @Override
            public void handle(WorkerStateEvent event){
                ProgressBarBonReceptionFrs.setVisible(false);
                ButtonSearchBonReceptionFrs.setDisable(false);
            }
        });
        ThreadSearchBonReceptionGestionFrs.start();
    }
  
    private void GestionSearchBonReceptionFrs()
    {
        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;
                NextLastSearchBonReceptionGestionFrs(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;
                    NextLastSearchBonReceptionGestionFrs(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;
                    NextLastSearchBonReceptionGestionFrs(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;
                    NextLastSearchBonReceptionGestionFrs(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;
                    NextLastSearchBonReceptionGestionFrs(position, nbrligne);
                    actuellepage=actuellepage-3 ;
                    ActuellePage.setText(Integer.toString(actuellepage));
                }
            }
        });

    }
    
}
