/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Controllers.FactureFrs;


import Models.FactureFrs.FactureFrs;
import Models.FactureFrs.FactureFrsDB;
import Models.Fournisseur.FournisseurDB;
import Models.Stock.StockDB;
import com.gluonhq.charm.glisten.control.ProgressBar;
import java.io.IOException;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.ResourceBundle;
import javafx.beans.property.SimpleStringProperty;
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.TableColumn.CellDataFeatures;
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.controlsfx.control.textfield.TextFields;

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

    @FXML private AnchorPane AnchorPaneFactureFrsGestion ;
    
    @FXML private ProgressBar ProgressBarFactureFrs;
    
    @FXML private Button ButtonSearchFactureFrs;
    
    @FXML public TableView<FactureFrs> TableViewBonReception;
    @FXML public TableColumn<FactureFrs ,String> TabColNumero;
    @FXML public TableColumn<FactureFrs ,String> TabColFrs;
    @FXML public TableColumn<FactureFrs ,String> TabColDate;
    @FXML public TableColumn<FactureFrs ,String> TabColHeur;
    @FXML public TableColumn<FactureFrs ,String> TabColLocalReception;
    @FXML public TableColumn<FactureFrs ,String> TabColNetPayer;
    @FXML public TableColumn<FactureFrs ,Boolean>TabColDetail ;
    
    @FXML public TextField  TextFieldNumero ;
    @FXML public TextField  TextFieldFournisseur ;
    @FXML public DatePicker DatePickerDateReception;
    @FXML public ChoiceBox ChoiceBoxLocalReception ;
    
    @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 ;
    
    private Service<Void> ThreadSearchFactureFrs;
    
    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;
    
    String LocalReception = "";
    String IdFournisseur = "";
    
    public  ArrayList<String> ListFournisseur = new  ArrayList<>();
    public  ArrayList<String> ListLocale = new  ArrayList<>();
    
    DecimalFormat Formatter = new DecimalFormat("##,###.## ");
    
    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        
        NbrLigne.setItems(cursors);
        NbrLigne.getSelectionModel().selectFirst();
        
        setDefaultFormData();
        
        TabColNumero.setCellValueFactory(new PropertyValueFactory<FactureFrs, String>("Numero"));
        
        TabColFrs.setStyle( "-fx-alignment: CENTER; -fx-font-weight:bold; -fx-font-size: 10pt;");
        TabColFrs.getStyleClass().add("Center");
        TabColFrs.setCellValueFactory(new Callback<CellDataFeatures<FactureFrs,String>, ObservableValue<String>>() {
            @Override
            public ObservableValue<String> call(CellDataFeatures<FactureFrs, String> data) {
                return new SimpleStringProperty(data.getValue().getFournisseur().getNom());
            }
        });
    
        TabColDate.setCellValueFactory(new PropertyValueFactory<FactureFrs, String>("DateCreation"));
        TabColDate.setStyle( "-fx-alignment: CENTER; -fx-font-weight:bold; -fx-font-size: 10pt;");
        TabColDate.getStyleClass().add("Center");
        
        TabColHeur.setCellValueFactory(new PropertyValueFactory<FactureFrs, String>("HeurCreation"));
        TabColHeur.setStyle( "-fx-alignment: CENTER; -fx-font-weight:bold; -fx-font-size: 10pt;");
        TabColHeur.getStyleClass().add("Center");
        
        TabColLocalReception.setCellValueFactory(new PropertyValueFactory<FactureFrs, String>("Local"));
        TabColLocalReception.setStyle( "-fx-alignment: CENTER; -fx-font-weight:bold; -fx-font-size: 10pt;");
        TabColLocalReception.getStyleClass().add("Center");
        
        TabColNetPayer.setCellValueFactory(new PropertyValueFactory<FactureFrs, String>("NetAPayer"));
        TabColNetPayer.setStyle( "-fx-alignment: CENTER; -fx-font-weight:bold; -fx-font-size: 10pt;");
        TabColNetPayer.getStyleClass().add("Center");
        TabColNetPayer.setCellFactory(new Callback<TableColumn<FactureFrs,String>,TableCell<FactureFrs,String>>(){        
            @Override
            public TableCell<FactureFrs, String> call(TableColumn<FactureFrs, String> param) {                
                TableCell<FactureFrs, String> cell = new TableCell<FactureFrs, String>(){
                    @Override
                    public void updateItem(String item, boolean empty) {
                        if(item!= null){
                            Text text = new Text(Formatter.format(Float.parseFloat(item)));
                            setGraphic(text);
                        }else{
                            setGraphic(null);
                        }
                    }
                };                           
                return cell;
            }
        });
        
        TabColDetail.setStyle( "-fx-alignment: CENTER;");TabColDetail.getStyleClass().add("Center");
        TabColDetail.setCellFactory(new Callback<TableColumn<FactureFrs, Boolean>, TableCell<FactureFrs, Boolean>>() {
            @Override 
            public TableCell<FactureFrs, Boolean> call(TableColumn<FactureFrs, Boolean> personBooleanTableColumn) {
                return new ButtonCell();
            }
        });
        
        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];
                }
            } 
        });
        
        ChoiceBoxLocalReception.valueProperty().addListener(new ChangeListener<String>() {
            @Override 
            public void changed(ObservableValue ov, String t, String ValLocal) {
                LocalReception = ValLocal;
            }    
        });
        
        ButtonSearchFactureFrs.setOnMouseClicked(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent me) {
                SearchFactureFrs();
            }
        });
        
        AnchorPaneFactureFrsGestion.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent ke) {
                if (ke.getCode().equals(KeyCode.ENTER)) {
                    SearchFactureFrs();
                }
            }
        });
        
        GestionSearchFactureFrs();
    }    
    
    
    
    private class ButtonCell extends TableCell<FactureFrs, 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 {
                        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/Views/FactureFrs/FactureFrsDetail.fxml"));
                        Parent ParentFxmlFournisseur = (Parent)fxmlLoader.load();
                        
                        FactureFrs FournisseurList = ((FactureFrs)getTableRow().getItem());
                        
                        FactureFrsDetailController FactureFrsDetail = fxmlLoader.getController();
                        FactureFrsDetail.setDataFactureDetailFrs(FournisseurList.getIdFactureFrs());
                        FactureFrsDetail.PaneSucessFrs.setVisible(false);
                        
                        AnchorPaneFactureFrsGestion.getChildren().clear();
                        AnchorPaneFactureFrsGestion.getChildren().add(ParentFxmlFournisseur);
                    } catch (Exception ex) {
                        System.err.println("FactureFrsGestionController ButtonCell ! \n"+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 FactureFrsBonReceptionAjouterButtonAction(ActionEvent event) throws IOException {
       AnchorPaneFactureFrsGestion.getChildren().clear();
       AnchorPaneFactureFrsGestion.getChildren().add((Node) FXMLLoader.load(getClass().getResource("/Views/FactureFrs/FactureFrsBonReceptionAjouter.fxml")));
    }
    
    
    @FXML
    private void FactureFrsAjouterButtonAction(ActionEvent event) throws IOException {
       AnchorPaneFactureFrsGestion.getChildren().clear();
       AnchorPaneFactureFrsGestion.getChildren().add((Node) FXMLLoader.load(getClass().getResource("/Views/FactureFrs/FactureFrsAjouter.fxml")));
    }
    
    private void setDefaultFormData()
    {
        ProgressBarFactureFrs.setVisible(true);
        
        ThreadSearchFactureFrs = new Service<Void>(){
            @Override
            protected Task<Void> createTask(){
                return new Task<Void>(){
                    @Override
                    protected Void call() throws Exception{
                        
                        ListFournisseur = new FournisseurDB().getAllFournisseur("CONCAT(`id_fourisseur`,' - ',`nom`)");
                        TextFields.bindAutoCompletion(TextFieldFournisseur, ListFournisseur);
        
                        ListLocale = new StockDB().getAllListLocal();
                        ChoiceBoxLocalReception.getItems().addAll(ListLocale);
                        return null;
                    }
                };
            }
	};
        ThreadSearchFactureFrs.setOnSucceeded(new EventHandler<WorkerStateEvent>(){
            @Override
            public void handle(WorkerStateEvent event){
                ProgressBarFactureFrs.setVisible(false);
                
            }
        });
        ThreadSearchFactureFrs.start();
    }
    
/******************************************************************************                                                                             *
 *                                                                              *
 *        Methode last Next TableView                                           *
 * *                                                                            *
 ******************************************************************************/  
    
    private void SearchFactureFrs()
    {
        ProgressBarFactureFrs.setVisible(true);
        
        ButtonSearchFactureFrs.setDisable(true);
        
        ThreadSearchFactureFrs = 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<FactureFrs> ListFactureFrss = new FactureFrsDB().SearchFactureFrsGestion(
                                                                                        position, 
                                                                                        nbrligne, 
                                                                                        TextFieldNumero.getText(), 
                                                                                        IdFournisseur,
                                                                                        LocalReception,
                                                                                        DateReception);
                            
                        TableViewBonReception.setItems(ListFactureFrss);
                        
                        totalcount = new FactureFrsDB().nbrFactureFrsGestion(TextFieldNumero.getText(), IdFournisseur, LocalReception, DateReception);
                        
                        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;
                    }
                };
            }
	};
        
        ThreadSearchFactureFrs.setOnSucceeded(new EventHandler<WorkerStateEvent>(){
            @Override
            public void handle(WorkerStateEvent event){
                ProgressBarFactureFrs.setVisible(false);
                ButtonSearchFactureFrs.setDisable(false);
                LabelCount.setText(totalcount.toString());
                
            }
        });
        ThreadSearchFactureFrs.start();
    }
    
    
    private void NextLastSearchFactureFrs(Integer ParmPosition, Integer ParamNbrligne)
    {
        ProgressBarFactureFrs.setVisible(true);
        
        ButtonSearchFactureFrs.setDisable(true);
        
        ThreadSearchFactureFrs = 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<FactureFrs> ListFactureFrs = new FactureFrsDB().SearchFactureFrsGestion(ParmPosition, ParamNbrligne, TextFieldNumero.getText(), IdFournisseur, LocalReception, DateReception);
                        
                        TableViewBonReception.setItems(ListFactureFrs);
                        
                        return null;
                    }
                };
            }
	};
        
        ThreadSearchFactureFrs.setOnSucceeded(new EventHandler<WorkerStateEvent>(){
            @Override
            public void handle(WorkerStateEvent event){
                ProgressBarFactureFrs.setVisible(false);
                ButtonSearchFactureFrs.setDisable(false);
            }
        });
        ThreadSearchFactureFrs.start();
    }
  
    private void GestionSearchFactureFrs()
    {
        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;
                NextLastSearchFactureFrs(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;
                    NextLastSearchFactureFrs(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;
                    NextLastSearchFactureFrs(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;
                    NextLastSearchFactureFrs(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;
                    NextLastSearchFactureFrs(position, nbrligne);
                    actuellepage=actuellepage-3 ;
                    ActuellePage.setText(Integer.toString(actuellepage));
                }
            }
        });

    }
  
    
}
