
package Controllers.ChequeClt;

import Controllers.Traitement.Adaptateur;
import Controllers.Traitement.MyWindow;
import Models.ChequeClt.ChequeClt;
import Models.ChequeClt.ChequeCltDB;
import Models.ChequeClt.ChequeCltHistoriqueListe;
import java.io.IOException;
import org.apache.log4j.Logger;
import javafx.application.Platform;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.util.Callback;

/**
 * FXML Controller class
 * @author Maher
 */
public class ChequeCltDetailController {
    
    Logger logger = Logger.getLogger(ChequeCltDetailController.class.getName());
    
    @FXML public AnchorPane AnchorPrincipal ; 
    @FXML private AnchorPane AnchorSecondaire;
    
    @FXML private ProgressIndicator ProgressCheque;
    
    @FXML private Text TextTypeClt;
    @FXML private Text TextCode;
    @FXML private Text TextNom;
    @FXML private Text TextPrenom;
    @FXML private Text TextTele1;
    @FXML private Text TextTele2;
    @FXML private Text TextAdress;
    
    @FXML private Text TextNumCheque1;
    @FXML private Text TextNumCheque2;
    @FXML private Text TextBanque;
    @FXML private Text TextDateCheque;
    @FXML private Text TextMontant;
    @FXML private Text TextFacture;
    @FXML private Text TextUtilisateur;
    
    @FXML private RadioButton RadioVerser;
    @FXML private RadioButton RadioSansProvision;
    @FXML private RadioButton RadioContreCheque;
     
    @FXML private Button UpdateEtatButton;
    @FXML public Button ButtonExitChequeCltDetail;
    
    @FXML public TableView<ChequeCltHistoriqueListe> TableViewChequeCltHistorique;
    
    @FXML public TableColumn<ChequeCltHistoriqueListe ,String> TabColDate;
    @FXML public TableColumn<ChequeCltHistoriqueListe ,String> TabColHeur;
    @FXML public TableColumn<ChequeCltHistoriqueListe ,Integer> TabColEtat;
    @FXML public TableColumn<ChequeCltHistoriqueListe ,String> TabColUtili;
    
    public Node nodeFxml;
    public String IdChequeClt;
    public String LastEtat;
    public Integer Source;
    ChequeClt Cheque = new ChequeClt();
    
    public  ChequeCltDetailController(){
        try {
            FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/Views/ChequeClt/ChequeCltDetail.fxml"));
            fxmlLoader.setController(this);
            nodeFxml = (Node) fxmlLoader.load();
        } catch (IOException ex) {
            logger.error("ChequeCltDetailController  : ChequeCltDetail.fxml :" + ex.getMessage());
        }
    }   
    
    public void Show()
    {
        StackPane Sp = new StackPane();
            
        Scene scene = new Scene(Sp);
        
        Sp.setPrefSize((double)MyWindow.PrincipalContentWidth, (double)MyWindow.PrincipalContentHeight);
        
        Stage stage = MyWindow.myStage;
        
        Sp.getChildren().add(MyWindow.myParent);
        Sp.getChildren().add(nodeFxml);
            
        stage.setScene(scene);
        stage.show();
    }
    
    public void ControleUpdateEtatButton(){
        
        if(Cheque.getLastEtat() != null){
            if(Cheque.getLastEtat() == 2){
                UpdateEtatButton.setDisable(true);
            }else{
                RadioVerser.setOnMouseClicked(new EventHandler<MouseEvent>() {
                    public void handle(MouseEvent me) {
                        if(Cheque.getLastEtat() == 1){
                            UpdateEtatButton.setDisable(true);
                        }else if((Cheque.getLastEtat() == 0) || (Cheque.getLastEtat() == 1)){
                            UpdateEtatButton.setDisable(false);
                        }
                    }
                });


                RadioSansProvision.setOnMouseClicked(new EventHandler<MouseEvent>() {
                    public void handle(MouseEvent me) {
                        if(Cheque.getLastEtat() == 0){
                             UpdateEtatButton.setDisable(true);
                        }else if((Cheque.getLastEtat() == 1) || (Cheque.getLastEtat() == 2)){
                            UpdateEtatButton.setDisable(false);
                        }
                    }
                });
           }
        }
        
        
        
        
    }
    
    public void Initialize(String id_cheque, Integer source) {
        IdChequeClt = id_cheque;
        Source = source;// 0==>Cheque(table cheque_clt)  1==>Traite(table traite_paiement_cheque_clt)
        
        TabColDate.setStyle( "-fx-alignment: CENTER;");
        TabColDate.getStyleClass().add("Center");
        TabColDate.setCellValueFactory(new PropertyValueFactory<ChequeCltHistoriqueListe, String>("DateOperation"));
        
        TabColHeur.setStyle( "-fx-alignment: CENTER;");
        TabColHeur.getStyleClass().add("Center");
        TabColHeur.setCellValueFactory(new PropertyValueFactory<ChequeCltHistoriqueListe, String>("HeurOperation"));
        
        TabColEtat.setStyle( "-fx-alignment: CENTER;");
        TabColEtat.getStyleClass().add("Center");
        TabColEtat.setCellValueFactory(new PropertyValueFactory("Etat"));
        TabColEtat.setCellValueFactory(new PropertyValueFactory<ChequeCltHistoriqueListe, Integer>("Etat"));
        TabColEtat.setCellFactory(new Callback<TableColumn<ChequeCltHistoriqueListe,Integer>,TableCell<ChequeCltHistoriqueListe,Integer>>(){        
            @Override
            public TableCell<ChequeCltHistoriqueListe, Integer> call(TableColumn<ChequeCltHistoriqueListe, Integer> param) {                
                TableCell<ChequeCltHistoriqueListe, Integer> cell = new TableCell<ChequeCltHistoriqueListe, Integer>(){
                    @Override
                    public void updateItem(Integer item, boolean empty) {
                        // 0 cheque sans provision     1 Verser (Valider)   2 Contre chéque(espace)
                        if(item!= null && item == 0){
                            Text text = new Text("chèque sans provision");
                            text.setFill(Color.web("#EA4335"));
                            text.setFont(Font.font("Arial", FontWeight.BOLD, 14));
                            setGraphic(text);
                        }else if(item!= null && item == 1){
                            Text text = new Text("verser");
                            text.setFill(Color.web("#428BCA"));
                            text.setFont(Font.font("Arial", FontWeight.BOLD, 14));
                            setGraphic(text);
                        }else if(item!= null && item == 2){
                            Text text = new Text("contre chèque");
                            text.setFill(Color.web("#34A853"));
                            text.setFont(Font.font("Arial", FontWeight.BOLD, 14));
                            setGraphic(text);
                        }else{
                            setGraphic(null);
                        }
                    }
                };                           
                return cell;
            }
        });
        
        TabColUtili.setStyle( "-fx-alignment: CENTER;");
        TabColUtili.getStyleClass().add("Center");
        TabColUtili.setCellValueFactory(new PropertyValueFactory<ChequeCltHistoriqueListe, String>("Utilisateur"));
        
        ButtonUpdateEtatAction();
        
        startTask();
        
    }
    
    
    public void startTask(){
        
        ProgressCheque.setVisible(true);
        AnchorSecondaire.setVisible(false);
                
        // Create a Runnable
        Runnable task = new Runnable(){
            public void run(){
                Platform.runLater(new Runnable(){
                    @Override
		    public void run(){
                        SetIdChequeClt();
                        ProgressCheque.setVisible(false);
                        AnchorSecondaire.setVisible(true);
		    }
		});	
            }
	};
        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
    }
    
    
    
    
    
    public void SetIdChequeClt(){
        ChequeCltDB ChequeDB = new ChequeCltDB();
        Cheque = ChequeDB.getChequeClt(IdChequeClt, Source);
        
        Integer TypeClt = Cheque.getTypeClient();
        if(TypeClt == 0){
            TextTypeClt.setText("Ancien");
            TextCode.setText(Cheque.getCltPersonne().getCodeclient());
            TextNom.setText(Cheque.getCltPersonne().getNom());
            TextPrenom.setText(Cheque.getCltPersonne().getPrenom());
            TextTele1.setText(Cheque.getCltPersonne().getTelefixString());
            TextTele2.setText(Cheque.getCltPersonne().getTelemobileString());
            TextAdress.setText(Cheque.getCltPersonne().getAdresse());  
        }else if(TypeClt == 1){
            TextTypeClt.setText("Entreprise");
            TextCode.setText(Cheque.getCltEntreprise().getCodeString());
            TextNom.setText(Cheque.getCltEntreprise().getNom());
            TextPrenom.setText(Cheque.getCltEntreprise().getMatricule());
            TextTele1.setText(Cheque.getCltEntreprise().getTele1String());
            TextTele2.setText(Cheque.getCltEntreprise().getTele2String());
            TextAdress.setText(Cheque.getCltEntreprise().getAdresse()); 
        }else if(TypeClt == 2){
            TextTypeClt.setText("Passager");
            TextCode.setText(Cheque.getCltPassager().getCodeclient());
            TextNom.setText(Cheque.getCltPassager().getNom());
            TextPrenom.setText(Cheque.getCltPassager().getPrenom());
            TextTele1.setText(Cheque.getCltPassager().getTelefixString());
            TextTele2.setText(Cheque.getCltPassager().getTelemobileString());
            TextAdress.setText(Cheque.getCltPassager().getAdresse()); 
        }
        
        TextNumCheque1.setText(Cheque.getNumeroChequeClt());
        TextNumCheque2.setText(Cheque.getNumeroChequeClt());
        TextBanque.setText(Cheque.getBanqueChequeClt());
        TextDateCheque.setText(Cheque.getDatePaiement());
        TextMontant.setText(Adaptateur.FloatToStringEspaceCurrency(Cheque.getMontantFloatChequeClt()));
        TextFacture.setText(Cheque.getCodeFactureClt());
        TextUtilisateur.setText(Cheque.getProfile().getNom()+" "+Cheque.getProfile().getPrenom());
        
        //Etat     0 cheque sans provision     1 Verser (Valider)   2 Contre chéque(espace)
        if(Cheque.getLastEtat() != null){
            if(Cheque.getLastEtat() == 1){
                RadioVerser.setSelected(true);
                UpdateEtatButton.setDisable(true);
            }else if(Cheque.getLastEtat() == 0){
                RadioSansProvision.setSelected(true);
                UpdateEtatButton.setDisable(true);
            }else if(Cheque.getLastEtat() == 2){
                RadioContreCheque.setSelected(true);
                UpdateEtatButton.setDisable(true);
            }
        }
        
        ObservableList<ChequeCltHistoriqueListe> ObservableListHistChequeClt = Cheque.getHistoriqueListe();
        Integer LastListHistCheque = ObservableListHistChequeClt.size()-1;
        if(LastListHistCheque>=0){
            LastEtat = ObservableListHistChequeClt.get(LastListHistCheque).getEtat().toString();
        }
        
        TableViewChequeCltHistorique.setItems(ObservableListHistChequeClt);
        
        ControleUpdateEtatButton();
    }
    
    
    public void ButtonUpdateEtatAction(){
        UpdateEtatButton.setOnAction(new EventHandler<ActionEvent>() {     //supprimer le message du suucés et reaficher les formulaires  
            @Override
            public void handle(ActionEvent event) {
                boolean isSelectedVerser = RadioVerser.isSelected();
                boolean isSelectedProvision = RadioSansProvision.isSelected();
                boolean isSelectedContre = RadioContreCheque.isSelected();

                ChequeCltDB ChequeDB = new ChequeCltDB();

                //Etat     0 cheque sans provision     1 Verser (Valider)   2 Contre chéque(espace)
                //Source   0==>Cheque(table cheque_clt)  1==>Traite(table traite_paiement_cheque_clt)
                if(isSelectedVerser == true){
                    ChequeDB.setHistoriqueCheque(1, Source, Cheque);
                }else if(isSelectedProvision == true){
                    ChequeDB.setHistoriqueCheque(0, Source, Cheque);
                }else if(isSelectedContre == true){
                    ChequeDB.setHistoriqueCheque(2, Source, Cheque);
                }
                startTask();
            }
        });
    }
    
    
   
    
}
