package Controllers.Caisse;

import Models.Caisse.Frais;
import Models.Caisse.FraisDB;
import Models.Stock.StockDB;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Group;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.ComboBox;
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 com.gluonhq.charm.glisten.control.ProgressBar;
import java.io.IOException;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.concurrent.WorkerStateEvent;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
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
 */
public class FraisGestionController implements Initializable {

    @FXML private AnchorPane PaneGestionFrais ;
    
    @FXML private TextField TextFieldCodeFrais;
    @FXML private TextField TextFieldObject;
    @FXML private TextField TextFieldPresonne;
    
    @FXML private ComboBox ComboBoxLocale ;
    @FXML private ComboBox ComboBoxPaiement;
    @FXML private DatePicker DatePickerCreate;
    
    @FXML private ProgressBar ProgressBarFraisGestion;
    @FXML private Button ButtonSearchFraisGestion;
    
    @FXML private TableView<Frais> TableViewFrais;
    @FXML private TableColumn<Frais ,String> TabColIdFrais;
    @FXML private TableColumn<Frais ,String> TabColMontant;
    @FXML private TableColumn<Frais ,String> TabColObject;
    @FXML private TableColumn<Frais ,String> TabColDateCreation;
    @FXML private TableColumn<Frais ,String> TabColPaiement;
    @FXML private TableColumn<Frais ,String> TabColProfile;
    @FXML private TableColumn<Frais ,String> TabColLocalNom;
    @FXML private TableColumn<Frais ,Boolean>TabColDetail ;
    
    @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> ThreadSearchFraisGestion;
    
    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        
        NbrLigne.setItems(cursors);
        NbrLigne.getSelectionModel().selectFirst();
        
        ComboBoxLocale.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent t) {
                if(ComboBoxLocale.getItems().size() == 0){
                    ComboBoxLocale.getItems().addAll(new StockDB().getAllListLocal());
                }
            }
        });
        
        //0:Espèce   1:Chèque    2 :carte bancaire
        ComboBoxPaiement.setItems(FXCollections.observableArrayList("Espèces","Chèque","Carte Bancaire"));
                
        TabColIdFrais.setStyle( "-fx-alignment: CENTER;");TabColIdFrais.getStyleClass().add("Center");
        TabColIdFrais.setCellValueFactory(new PropertyValueFactory<Frais, String>("IdFrais"));
        
        TabColMontant.setStyle( "-fx-alignment: CENTER;");TabColMontant.getStyleClass().add("Center");
        TabColMontant.setCellValueFactory(new PropertyValueFactory<Frais, String>("Montant"));
        
        TabColObject.setStyle( "-fx-alignment: CENTER;");TabColObject.getStyleClass().add("Center");
        TabColObject.setCellValueFactory(new PropertyValueFactory<Frais, String>("Object"));
        
        TabColDateCreation.setStyle( "-fx-alignment: CENTER;");TabColDateCreation.getStyleClass().add("Center");
        TabColDateCreation.setCellValueFactory(new PropertyValueFactory<Frais, String>("DateCreation"));
        
        TabColPaiement.setStyle( "-fx-alignment: CENTER;");TabColPaiement.getStyleClass().add("Center");
        TabColPaiement.setCellValueFactory(new PropertyValueFactory<Frais, String>("Paiement"));
        TabColPaiement.setCellFactory(new Callback<TableColumn<Frais,String>,TableCell<Frais,String>>(){        
            @Override
            public TableCell<Frais, String> call(TableColumn<Frais, String> param) {                
                TableCell<Frais, String> cell = new TableCell<Frais, String>(){
                    @Override
                    public void updateItem(String item, boolean empty) {
                        ////0 :espace   1:Chèque    2 :carte bancaire
                        if(item!=null && item.equals("0")){
                            Text text = new Text("Espèce");
                            text.setFont(Font.font("Arial", FontWeight.NORMAL, 14));
                            setGraphic(text);
                        }else if(item!=null && item.equals("1")){
                            Text text = new Text("Chèque");
                            text.setFont(Font.font("Arial", FontWeight.NORMAL, 14));
                            setGraphic(text);
                        }else if(item!=null && item.equals("2")){
                            Text text = new Text("Carte Bancaire");
                            text.setFont(Font.font("Arial", FontWeight.NORMAL, 14));
                            setGraphic(text);
                        }else{
                            setGraphic(null);
                        }
                    }
                };                           
                return cell;
            }
        });
        
        TabColProfile.setStyle( "-fx-alignment: CENTER;");TabColProfile.getStyleClass().add("Center");
        TabColProfile.setCellValueFactory(new PropertyValueFactory<Frais, String>("Profile"));
        
        TabColLocalNom.setStyle( "-fx-alignment: CENTER;");TabColLocalNom.getStyleClass().add("Center");
        TabColLocalNom.setCellValueFactory(new PropertyValueFactory<Frais, String>("LocalNom"));
        
        TabColDetail.setSortable(true);
        TabColDetail.setStyle( "-fx-alignment: CENTER;");TabColDetail.getStyleClass().add("Center");
        TabColDetail.setCellFactory(new Callback<TableColumn<Frais, Boolean>, TableCell<Frais, Boolean>>() {
          @Override 
          public TableCell<Frais, Boolean> call(TableColumn<Frais, Boolean> personBooleanTableColumn) {
            return new ButtonCell();
          }
        });
        
        
        ButtonSearchFraisGestion.setOnMouseClicked(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent me) {
                SearchFraisGestion();
            }
        });
        
        PaneGestionFrais.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent ke) {
                if (ke.getCode().equals(KeyCode.ENTER)) {
                    SearchFraisGestion();
                }
            }
        });
        
        GestionSearchFournisseur();
        
    }


    
    //Define the button cell
    private class ButtonCell extends TableCell<Frais, 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) {
                    Frais frais = ((Frais)getTableRow().getItem());
                    FraisDetailController FraisDetail = new FraisDetailController();
                    FraisDetail.LanchShowFrais(frais.getIdFrais());
                    FraisDetail.Show();
                    
                }
            });
        }
        //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 AjouterFraisButtonAction(ActionEvent event) throws IOException {
       PaneGestionFrais.getChildren().clear();
       PaneGestionFrais.getChildren().add((Node) FXMLLoader.load(getClass().getResource("/Views/Caisse/FraisAjouter.fxml")));
    }
    
    
/******************************************************************************                                                                             *
 *                                                                              *
 *                       Methode last Next TableView 		                *
 * *                                                                            *
 ******************************************************************************/  
 
    private void SearchFraisGestion()
    {
        ProgressBarFraisGestion.setVisible(true);
        
        ButtonSearchFraisGestion.setDisable(true);
        
        ThreadSearchFraisGestion = 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(DatePickerCreate.getValue() != null){
                            DateCreation = DatePickerCreate.getValue().toString();
                        }
                        
                        ObservableList<Frais> ListFraisGestions = new FraisDB().SearchFraisGestion(
                                                                                        position, 
                                                                                        nbrligne, 
                                                                                        TextFieldCodeFrais.getText(),
                                                                                        TextFieldObject.getText(),
                                                                                        TextFieldPresonne.getText(),
                                                                                        (String) ComboBoxLocale.getValue(),
                                                                                        (String) ComboBoxPaiement.getValue(),
                                                                                        DateCreation);
                            
                        TableViewFrais.setItems(ListFraisGestions);
                        
                        totalcount = new FraisDB().nbrFraisGestion(TextFieldCodeFrais.getText(), TextFieldObject.getText(), TextFieldPresonne.getText(), (String) ComboBoxLocale.getValue(), (String) ComboBoxPaiement.getValue(), 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;
                    }
                };
            }
	};
        
        ThreadSearchFraisGestion.setOnSucceeded(new EventHandler<WorkerStateEvent>(){
            @Override
            public void handle(WorkerStateEvent event){
                ProgressBarFraisGestion.setVisible(false);
                ButtonSearchFraisGestion.setDisable(false);
                LabelCount.setText(totalcount.toString());
                
            }
        });
        ThreadSearchFraisGestion.start();
    }
    
    
    private void NextLastSearchFraisGestion(Integer ParmPosition, Integer ParamNbrligne)
    {
        ProgressBarFraisGestion.setVisible(true);
        
        ButtonSearchFraisGestion.setDisable(true);
        
        ThreadSearchFraisGestion = new Service<Void>(){
            @Override
            protected Task<Void> createTask(){
                return new Task<Void>(){
                    @Override
                    protected Void call() throws Exception{
                        
                        String DateCreation = "";
                        if(DatePickerCreate.getValue() != null){
                            DateCreation = DatePickerCreate.getValue().toString();
                        }
                        
                        ObservableList<Frais> ListFraisGestions = new FraisDB().SearchFraisGestion(ParmPosition, ParamNbrligne, TextFieldCodeFrais.getText(), TextFieldObject.getText(), TextFieldPresonne.getText(), (String) ComboBoxLocale.getValue(), (String) ComboBoxPaiement.getValue(), DateCreation);
                        
                        TableViewFrais.setItems(ListFraisGestions);
                        
                        return null;
                    }
                };
            }
	};
        
        ThreadSearchFraisGestion.setOnSucceeded(new EventHandler<WorkerStateEvent>(){
            @Override
            public void handle(WorkerStateEvent event){
                ProgressBarFraisGestion.setVisible(false);
                ButtonSearchFraisGestion.setDisable(false);
            }
        });
        ThreadSearchFraisGestion.start();
    }
  
    private void GestionSearchFournisseur()
    {
        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;
                NextLastSearchFraisGestion(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;
                    NextLastSearchFraisGestion(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;
                    NextLastSearchFraisGestion(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;
                    NextLastSearchFraisGestion(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;
                    NextLastSearchFraisGestion(position, nbrligne);
                    actuellepage=actuellepage-3 ;
                    ActuellePage.setText(Integer.toString(actuellepage));
                }
            }
        });

    }   
}
