/*
 * 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.Reglement;

import Controllers.Dialog.MessageControle;
import Models.FactureFrs.FactureFrs;
import Models.FactureFrs.FactureFrsDB;
import Models.Fournisseur.FournisseurDB;
import Models.Stock.StockDB;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;
import javafx.application.Platform;
import javafx.beans.property.SimpleBooleanProperty;
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.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.ProgressIndicator;
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.KeyEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.util.Callback;
import org.controlsfx.control.textfield.TextFields;

/**
 * FXML Controller class
 *
 * @author Maher
 */
public class ReglementAjouter1Controller implements Initializable {

    @FXML private AnchorPane AnchorPaneReglementAjouter1;
    
    @FXML private ProgressIndicator ProgressFactureFrs;
    
    @FXML public TableView<FactureFrs> TableViewFactureFrs;
    @FXML public TableColumn<FactureFrs ,String> TabColNumero;
    @FXML public TableColumn<FactureFrs ,String> TabColFrs;
    @FXML public TableColumn<FactureFrs ,String> TabColDate;
    @FXML public TableColumn<FactureFrs ,String> TabColLocalReception;
    @FXML public TableColumn<FactureFrs ,String> TabColNetPayer;
    @FXML public TableColumn<FactureFrs ,Boolean>TabColDetail ;
    
    @FXML public TableView<FactureFrs> TableViewSeleFactureFrs;
    @FXML public TableColumn<FactureFrs ,String> TabColSeleNumero;
    @FXML public TableColumn<FactureFrs ,String> TabColSeleFrs;
    @FXML public TableColumn<FactureFrs ,String> TabColSeleDate;
    @FXML public TableColumn<FactureFrs ,String> TabColSeleHeur;
    @FXML public TableColumn<FactureFrs ,String> TabColSeleLocalReception;
    @FXML public TableColumn<FactureFrs ,String> TabColSeleNetPayer;
    @FXML public TableColumn<FactureFrs ,Boolean>TabColSeleSupprimer ;
    
    @FXML public TextField  TextFieldNumero ;
    @FXML private TextField TextFieldFournisseu ;
    @FXML public TextField  TextFieldNetAPayer ;
    @FXML public DatePicker DatePickerDateReception;
    
    @FXML public ChoiceBox ChoiceBoxLocalReception ;
    
    public  ArrayList<String> ListFournisseur = new  ArrayList<>();
    public  ArrayList<String> ListLocale = new  ArrayList<>();
    
    ObservableList<FactureFrs> DataSelectFacture = FXCollections.observableArrayList();
    
    public FactureFrsDB FactureDB = new FactureFrsDB();
    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        
        StockDB Stock = new StockDB();
        ListLocale = Stock.getAllListLocal();
        ChoiceBoxLocalReception.getItems().addAll(ListLocale);
        
        FournisseurDB FrsDB = new FournisseurDB();
        ListFournisseur = FrsDB.getIdNomFournisseur();
        TextFields.bindAutoCompletion(TextFieldFournisseu, ListFournisseur);
        
        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<TableColumn.CellDataFeatures<FactureFrs,String>, ObservableValue<String>>() {
            @Override
            public ObservableValue<String> call(TableColumn.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");
        
        
        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");
        
        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 ReglementAjouter1Controller.ButtonCell();
            }
        });
        
        
        
        TabColSeleNumero.setCellValueFactory(new PropertyValueFactory<FactureFrs, String>("Numero"));
        
        TabColSeleFrs.setStyle( "-fx-alignment: CENTER; -fx-font-weight:bold; -fx-font-size: 10pt;");
        TabColSeleFrs.getStyleClass().add("Center");
        TabColSeleFrs.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<FactureFrs,String>, ObservableValue<String>>() {
            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<FactureFrs, String> data) {
                return new SimpleStringProperty(data.getValue().getFournisseur().getNom());
            }
        });
        
        TabColSeleDate.setCellValueFactory(new PropertyValueFactory<FactureFrs, String>("DateCreation"));
        TabColSeleDate.setStyle( "-fx-alignment: CENTER; -fx-font-weight:bold; -fx-font-size: 10pt;");
        TabColSeleDate.getStyleClass().add("Center");
        
        TabColSeleHeur.setCellValueFactory(new PropertyValueFactory<FactureFrs, String>("HeurCreation"));
        TabColSeleHeur.setStyle( "-fx-alignment: CENTER; -fx-font-weight:bold; -fx-font-size: 10pt;");
        TabColSeleHeur.getStyleClass().add("Center");
        
        TabColSeleLocalReception.setCellValueFactory(new PropertyValueFactory<FactureFrs, String>("Local"));
        TabColSeleLocalReception.setStyle( "-fx-alignment: CENTER; -fx-font-weight:bold; -fx-font-size: 10pt;");
        TabColSeleLocalReception.getStyleClass().add("Center");
        
        TabColSeleNetPayer.setCellValueFactory(new PropertyValueFactory<FactureFrs, String>("NetAPayer"));
        TabColSeleNetPayer.setStyle( "-fx-alignment: CENTER; -fx-font-weight:bold; -fx-font-size: 10pt;");
        TabColSeleNetPayer.getStyleClass().add("Center");
        
        TabColSeleSupprimer.setStyle( "-fx-alignment: CENTER;");
        TabColSeleSupprimer.getStyleClass().add("Center");
        TabColSeleSupprimer.setSortable(true);
        
        TabColSeleSupprimer.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<FactureFrs, Boolean>, 
            ObservableValue<Boolean>>() {
            @Override
            public ObservableValue<Boolean> call(TableColumn.CellDataFeatures<FactureFrs, Boolean> p) {
                return new SimpleBooleanProperty(p.getValue() != null);
            }
        });

        // create a cell value factory with an add button for each row in the table.
        TabColSeleSupprimer.setCellFactory(new Callback<TableColumn<FactureFrs, Boolean>, TableCell<FactureFrs, Boolean>>() {
          @Override 
          public TableCell<FactureFrs, Boolean> call(TableColumn<FactureFrs, Boolean> personBooleanTableColumn) {
            return new ReglementAjouter1Controller.ButtonCellRemove();
          }
        });
        
       
        
        getChercherFactureFrs();
    }  
    
    @FXML
    private void DetailReglementButtonAction(ActionEvent event) throws IOException 
    {
        if(DataSelectFacture.size()>0){
            if(ControleListFacture()){
                FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/Views/Reglement/ReglementAjouter2.fxml"));
                Parent NodeReglementAjouter2 = (Parent)fxmlLoader.load();
            
                ReglementAjouter2Controller ReglementAjouter2 = fxmlLoader.getController();
                ReglementAjouter2.SetDataFactureFrs(DataSelectFacture);

                AnchorPaneReglementAjouter1.getChildren().clear();
                AnchorPaneReglementAjouter1.getChildren().add(NodeReglementAjouter2);
            }else{
                final MessageControle messagecontrol = new MessageControle();
                Text text3 = new Text();
                text3.setText("Les fournisseurs sélectionnés sont différents");
                text3.setFont(Font.font("Arial", FontWeight.BOLD, 13));
                text3.setFill(Color.web("#363a38"));
                messagecontrol.DetailMSG.getChildren().add(text3);

                messagecontrol.bouttonOK.setOnAction(new EventHandler<ActionEvent>() {
                    @Override
                    public void handle(ActionEvent event) {
                        messagecontrol.stackpane.setVisible(false);
                    }
                });
                messagecontrol.ShowNotification();
                
            }
            
        }else{
            final MessageControle messagecontrol = new MessageControle();
            Text text3 = new Text();
            text3.setText("Vous devez ajouter au moin une facture à la liste des factures");
            text3.setFont(Font.font("Arial", FontWeight.BOLD, 13));
            text3.setFill(Color.web("#363a38"));
            messagecontrol.DetailMSG.getChildren().add(text3);
            messagecontrol.bouttonOK.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    messagecontrol.stackpane.setVisible(false);
                }
            });
            messagecontrol.ShowNotification();
        }
        
    }
    
    
    private void getChercherFactureFrs(){
        TextFieldNumero.setOnKeyReleased(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent ke) {
                getDataFactureFrs("numero", " LIKE '"+TextFieldNumero.getText()+"%'");
            }
        });
        DatePickerDateReception.setOnAction(new EventHandler<ActionEvent>() {
            @Override 
            public void handle(ActionEvent actionEvent) {
                try{ 
                    getDataFactureFrs("to_char(date_creation, 'yyyy-mm-dd')", " = '"+DatePickerDateReception.getValue().toString()+"'");
                }catch(Exception ex){}
            }
        });
        DatePickerDateReception.setOnKeyReleased(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent ke) {
                try{
                    String DateReception = DatePickerDateReception.getConverter().fromString(DatePickerDateReception.getEditor().getText()).toString();
                    getDataFactureFrs("to_char(date_creation, 'yyyy-mm-dd')",  " = '"+DateReception+"'");
                }catch(Exception ex){}
            }
        });
        
        ChoiceBoxLocalReception.valueProperty().addListener(new ChangeListener<String>() {
            @Override 
            public void changed(ObservableValue ov, String t, String ValLocal) {
                getDataFactureFrs("local_reception",  " LIKE '"+ValLocal+"%'");
            }    
        });
        
        TextFieldNetAPayer.setOnKeyReleased(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent ke) {
                getDataFactureFrs("net_a_payer", "LIKE '"+TextFieldNetAPayer.getText()+"%'");
            }
        });
        
        TextFieldFournisseu.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);
                    getDataFactureFrs("id_fournisseur", " = "+array[0]);
                }
            } 
        });
        
        
    }
    
    public void setDataFactureFrs(ObservableList<FactureFrs> data_facture){
        DataSelectFacture = data_facture;
        TableViewSeleFactureFrs.setItems(data_facture);
        TableViewSeleFactureFrs.refresh();
    }
    
    private void getDataFactureFrs(final String tab, final String mot){
        
        ProgressFactureFrs.setVisible(true);
        TableViewFactureFrs.setItems(null);
        TableViewFactureFrs.setVisible(false);
        
        // Create a Runnable
        Runnable task = new Runnable(){
            public void run(){
                Platform.runLater(new Runnable(){
                    @Override
                    public void run(){
                        try {
                            ObservableList<FactureFrs> ListFactureFrs  = FactureDB.getDataFactureFrs(tab, mot, null, null);
                            TableViewFactureFrs.setItems(ListFactureFrs);
                            ProgressFactureFrs.setVisible(false);
                            TableViewFactureFrs.setVisible(true);
                            TableViewFactureFrs.refresh();
                        } catch (Exception ex) {
                            System.err.println("Erreur SQL ! \n"+ex.getMessage());
                        }
                    }
                });	
            }
        };
        Thread backgroundThread = new Thread(task); // Run the task in a background thread
        backgroundThread.setDaemon(true);   // Terminate the running thread if the application exits
        backgroundThread.start();   // Start the thread
    }
    
    
    private boolean ControleListFacture(){
        boolean result = true ;
        String CodeFirst  = DataSelectFacture.get(0).getFournisseur().getCode();
        for( FactureFrs FactSele : DataSelectFacture ) {
            if(!FactSele.getFournisseur().getCode().equals(CodeFirst)){
                result = false ;
                break;
            }
        }
        return result;
    }
    
    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/iconaffecter.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 {
                        FactureFrs ListFactureFrs = (FactureFrs) ButtonCell.this.getTableView().getItems().get(ButtonCell.this.getIndex());
                        
                        //Verifier si la Facture existe déja
                        boolean result = true ;
                        for( FactureFrs FactSele : DataSelectFacture ) {
                            if(FactSele.getNumero().equals(ListFactureFrs.getNumero())){
                                result = false ;
                                break;
                            }
                        }
                        if(result){
                            DataSelectFacture.add(ListFactureFrs);
                            TableViewSeleFactureFrs.setItems(DataSelectFacture);
                            TableViewSeleFactureFrs.refresh();
                        }
                        
                    } catch (Exception ex) {
                        System.err.println("ReglementAjouter1Controller 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);
            }
        }
    }
    
    
    //Define the button cell
    private class ButtonCellRemove extends TableCell<FactureFrs, Boolean> {
        
        final Button cellButton = new Button();
        
        ButtonCellRemove(){
            cellButton.getStyleClass().add("btn-danger");
            Image coffeeImage = new Image(getClass().getResourceAsStream("/Public/icon/icondelete.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) {
                    int selectdIndex = getTableRow().getIndex();
                    DataSelectFacture.remove(selectdIndex);
                    TableViewSeleFactureFrs.setItems(DataSelectFacture);
                    TableViewSeleFactureFrs.refresh();
                }
            });
        }
        //Display button if the row is not empty
        @Override
        protected void updateItem(Boolean t, boolean empty) {
            if(!empty){
                setGraphic(cellButton);
            } else {
                setGraphic(null);
            }
        }
    }
}
