package Controllers.FactureClt;

import Models.FactureClt.FactureCltDB;
import javafx.collections.FXCollections;
import Models.FactureClt.FactureCltGestionList;
import com.gluonhq.charm.glisten.control.ProgressBar;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
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.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.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.util.Callback;

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

    @FXML private AnchorPane PaneFactureGestion ;
    
    @FXML private ProgressBar ProgressBarFactureClt;
    
    @FXML private Button ButtonSearchFactureClt;
    
    @FXML public TableView<FactureCltGestionList> TableViewFactureCltListGestion;
    
    @FXML public TableColumn<FactureCltGestionList ,String> TabColCodeFacture;
    @FXML public TableColumn<FactureCltGestionList ,String> TabColTypeClient;
    @FXML public TableColumn<FactureCltGestionList ,String> TabColCodeClient;
    @FXML public TableColumn<FactureCltGestionList ,String> TabColMode ;
    @FXML public TableColumn<FactureCltGestionList ,String> TabColTotal;
    @FXML public TableColumn<FactureCltGestionList ,String> TabColCodeCommande;
    @FXML public TableColumn<FactureCltGestionList ,String> TabColCreation;
    @FXML public TableColumn<FactureCltGestionList ,Boolean>TabColDetail ;
    
    @FXML public TextField TextFieldCodeFacture ;
    @FXML public TextField TextFieldCodeClient ;
    @FXML public TextField TextFieldCodeCommande ;
    @FXML public DatePicker PickerDateCreation;
    
    @FXML public RadioButton RadioComptant;
    @FXML public RadioButton RadioFacilite;
    
    @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> ThreadSearchFactureClt;
            
    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;
    
    
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        
        //comboboxnombre des lignes tableview
        NbrLigne.setItems(cursors);
        NbrLigne.getSelectionModel().selectFirst();
        
        TableViewFactureCltListGestion.setEditable(true);
        
        TabColCodeFacture.setStyle( "-fx-alignment: CENTER;");TabColCodeFacture.getStyleClass().add("Center");
        TabColCodeFacture.setCellValueFactory(new PropertyValueFactory<FactureCltGestionList, String>("CodeFacture"));
        
        TabColTypeClient.setStyle( "-fx-alignment: CENTER;");TabColTypeClient.getStyleClass().add("Center");
        TabColTypeClient.setCellValueFactory(new PropertyValueFactory<FactureCltGestionList, String>("TypeClient"));
        
        TabColCodeClient.setStyle( "-fx-alignment: CENTER;");TabColCodeClient.getStyleClass().add("Center");
        TabColCodeClient.setCellValueFactory(new PropertyValueFactory<FactureCltGestionList, String>("CodeClient"));
        
        TabColMode.setStyle( "-fx-alignment: CENTER;");TabColMode.getStyleClass().add("Center");
        TabColMode.setCellValueFactory(new PropertyValueFactory<FactureCltGestionList, String>("Mode"));
        TabColMode.setCellFactory(new Callback<TableColumn<FactureCltGestionList,String>,TableCell<FactureCltGestionList,String>>(){        
            @Override
            public TableCell<FactureCltGestionList, String> call(TableColumn<FactureCltGestionList, String> param) {                
                TableCell<FactureCltGestionList, String> cell = new TableCell<FactureCltGestionList, String>(){
                    @Override
                    public void updateItem(String item, boolean empty) {
                        if(item!= null && item.equals("Comptant")){
                            Text text = new Text(item);
                            text.setFill(Color.web("#428BCA"));
                            text.setFont(Font.font("Arial", FontWeight.BOLD, 14));
                            setGraphic(text);
                        }else if(item!= null && item.equals("Facilité")){
                            Text text = new Text(item);
                            text.setFill(Color.web("#000000"));
                            text.setFont(Font.font("Arial", FontWeight.BOLD, 14));
                            setGraphic(text);
                        }else{
                            setGraphic(null);
                        }
                    }
                };                           
                return cell;
            }
        });
        
        TabColTotal.setStyle( "-fx-alignment: CENTER;");TabColTotal.getStyleClass().add("Center");
        TabColTotal.setCellValueFactory(new PropertyValueFactory<FactureCltGestionList, String>("Total"));
        
        TabColCodeCommande.setStyle( "-fx-alignment: CENTER;");TabColCodeCommande.getStyleClass().add("Center");
        TabColCodeCommande.setCellValueFactory(new PropertyValueFactory<FactureCltGestionList, String>("CodeCommande"));
        
        TabColCreation.setStyle( "-fx-alignment: CENTER;");TabColCreation.getStyleClass().add("Center");
        TabColCreation.setCellValueFactory(new PropertyValueFactory<FactureCltGestionList, String>("DateCreation"));
        
        TabColDetail.setStyle( "-fx-alignment: CENTER;");TabColDetail.getStyleClass().add("Center");
        TabColDetail.setCellFactory(new Callback<TableColumn<FactureCltGestionList, Boolean>, TableCell<FactureCltGestionList, Boolean>>() {
            @Override 
            public TableCell<FactureCltGestionList, Boolean> call(TableColumn<FactureCltGestionList, Boolean> personBooleanTableColumn) {
                return new ButtonCell();
            }
        });
        
       ButtonSearchFactureClt.setOnMouseClicked(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent me) {
                SearchFactureClt();
            }
        });
        
        PaneFactureGestion.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent ke) {
                if (ke.getCode().equals(KeyCode.ENTER)) {
                    SearchFactureClt();
                }
            }
        });
        
        RadioComptant.setOnMouseClicked(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent me) {
                SearchFactureClt();
            }
        });
        
        RadioFacilite.setOnMouseClicked(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent me) {
                SearchFactureClt();
            }
        });
        
        GestionSearchFactureClt();
        
    }    
    
    
    private class ButtonCell extends TableCell<FactureCltGestionList, 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 {
                        // get Selected Item
                        FactureCltGestionList current = (FactureCltGestionList) ButtonCell.this.getTableView().getItems().get(ButtonCell.this.getIndex());
                        String code_facture = current.getCodeFacture();
                        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/Views/FactureClt/FactureCltDetail.fxml"));
                        Parent NodeFactureCltDetail =  (Parent)fxmlLoader.load();
                        FactureCltDetailController FactureCltDetail= fxmlLoader.getController();
                        FactureCltDetail.PaneSucces.setVisible(false);
                        
                        FactureCltDetail.codeFactClt = code_facture;
                        FactureCltDetail.SowDetailFactureClt(false);
                        PaneFactureGestion.getChildren().clear();
                        PaneFactureGestion.getChildren().add(NodeFactureCltDetail);
                        FactureCltDetail.ButtonImprimerTraite.setVisible(false);
                    } catch (IOException ex) {
                        Logger.getLogger(FactureCltAjouterController.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    
                }
            });
        }
        
        //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 FactureCltAjouterButtonAction(ActionEvent event) throws IOException {
       PaneFactureGestion.getChildren().clear();
       PaneFactureGestion.getChildren().add((Node) FXMLLoader.load(getClass().getResource("/Views/FactureClt/FactureCltAjouter.fxml")));
    }
    
    
    
    
    
/******************************************************************************                                                                             *
 *                                                                              *
 *        Methode last Next TableView                                           *
 * *                                                                            *
 ******************************************************************************/  
    
    private void SearchFactureClt()
    {
        ProgressBarFactureClt.setVisible(true);
        
        ButtonSearchFactureClt.setDisable(true);
        
        ThreadSearchFactureClt = 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(PickerDateCreation.getValue() != null){
                            DateCreation = PickerDateCreation.getValue().toString();
                        }    
                        
                        //     0comptant        1facilité
                        String TypeRegement = "";
                        if(RadioComptant.isSelected()){
                            TypeRegement = "0";
                        }else if(RadioFacilite.isSelected()){
                            TypeRegement = "1";
                        }
                        
                        ObservableList<FactureCltGestionList> ListFactureClts = new FactureCltDB().SearchFactureCltGestion(
                                                                                        position, 
                                                                                        nbrligne, 
                                                                                        TextFieldCodeFacture.getText(), 
                                                                                        TextFieldCodeClient.getText(),  
                                                                                        TypeRegement, 
                                                                                        TextFieldCodeCommande.getText(), 
                                                                                        DateCreation);
                            
                        TableViewFactureCltListGestion.setItems(ListFactureClts);
                        
                        totalcount = new FactureCltDB().nbrFactureCltGestion(TextFieldCodeFacture.getText(), 
                                                                               TextFieldCodeClient.getText(),  
                                                                               TypeRegement, 
                                                                               TextFieldCodeCommande.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;
                    }
                };
            }
	};
        
        ThreadSearchFactureClt.setOnSucceeded(new EventHandler<WorkerStateEvent>(){
            @Override
            public void handle(WorkerStateEvent event){
                ProgressBarFactureClt.setVisible(false);
                ButtonSearchFactureClt.setDisable(false);
                LabelCount.setText(totalcount.toString());
                
            }
        });
        ThreadSearchFactureClt.start();
    }
    
    
    private void NextLastSearchFactureClt(Integer ParmPosition, Integer ParamNbrligne)
    {
        ProgressBarFactureClt.setVisible(true);
        
        ButtonSearchFactureClt.setDisable(true);
        
        ThreadSearchFactureClt = new Service<Void>(){
            @Override
            protected Task<Void> createTask(){
                return new Task<Void>(){
                    @Override
                    protected Void call() throws Exception{
                        
                        String DateCreation = "";
                        if(PickerDateCreation.getValue() != null){
                            DateCreation = PickerDateCreation.getValue().toString();
                        } 
                        
                        ObservableList<FactureCltGestionList> ListFactureClts = new FactureCltDB().SearchFactureCltGestion(ParmPosition, ParamNbrligne, TextFieldCodeFacture.getText(), TextFieldCodeClient.getText(), "",  TextFieldCodeCommande.getText(), DateCreation);
                        
                        TableViewFactureCltListGestion.setItems(ListFactureClts);
                        
                        return null;
                    }
                };
            }
	};
        
        ThreadSearchFactureClt.setOnSucceeded(new EventHandler<WorkerStateEvent>(){
            @Override
            public void handle(WorkerStateEvent event){
                ProgressBarFactureClt.setVisible(false);
                ButtonSearchFactureClt.setDisable(false);
            }
        });
        ThreadSearchFactureClt.start();
    }
  
    private void GestionSearchFactureClt()
    {
        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;
                NextLastSearchFactureClt(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;
                    NextLastSearchFactureClt(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;
                    NextLastSearchFactureClt(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;
                    NextLastSearchFactureClt(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;
                    NextLastSearchFactureClt(position, nbrligne);
                    actuellepage=actuellepage-3 ;
                    ActuellePage.setText(Integer.toString(actuellepage));
                }
            }
        });

    }
  
  
 
  
}
