package Controllers.FactureClt;

import Controllers.TraiteClt.TraiteCltPrintController;
import Controllers.Traitement.Adaptateur;
import Models.Produit.ListeProduit;
import Models.FactureClt.FactureClt;
import Models.FactureClt.FactureCltChequeListe;
import Models.FactureClt.FactureCltDB;
import Models.FactureClt.FactureCltTraiteListe;
import Models.ChequeClt.ChequeClt;
import Models.TraiteClt.TraiteClt;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;
import org.apache.log4j.Logger;
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.print.JobSettings;
import javafx.print.PageLayout;
import javafx.print.PageOrientation;
import javafx.print.PageRange;
import javafx.print.Paper;
import javafx.print.Printer;
import javafx.print.PrinterJob;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.Tab;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
import javafx.scene.text.Text;

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

    Logger logger = Logger.getLogger(FactureCltDetailController.class.getName());
    
    @FXML public AnchorPane PaneSucces;
    
    @FXML public AnchorPane AnchorPaneLoading;
    @FXML public AnchorPane AnchorPaneDetailFactureClt;
    
    @FXML private Text DateCreation;
    @FXML private Text Reglement;
    @FXML private Text NetAPayer;
    @FXML private Text TotalHorsTaxNet;
    @FXML private Text TotalTVA;
    @FXML private Text CodeFactClt;
    
    @FXML private Text TypeClt;
    @FXML private Text Nom;
    @FXML private Text Prenom;
    @FXML private Text Adresse;
    @FXML private Text TELE1;
    @FXML private Text TELE2;
    
    @FXML private Text TextPrenom ;
    @FXML private Text TextMatricule ;
    
    @FXML private Text TextMontant;
    @FXML private Text ValMontant;
    
    
    @FXML private TableView<ListeProduit> TableViewListeProduit ;
    @FXML private TableColumn<ListeProduit ,String> TabColReference;
    @FXML private TableColumn<ListeProduit ,String> TabColDesignation;
    @FXML private TableColumn<ListeProduit ,String> TabColQuantite ;
    @FXML private TableColumn<ListeProduit ,String> TabColPrixHT;
    @FXML private TableColumn<ListeProduit ,String> TabColRemise;
    @FXML private TableColumn<ListeProduit ,String> TabColTotalHT;
    @FXML private TableColumn<ListeProduit ,String> TabColTVA;
    @FXML private TableColumn<ListeProduit ,String> TabColTotalTTC;

    
    @FXML private TableView<FactureCltTraiteListe> TableViewListeTraites ;
    @FXML private TableColumn<FactureCltTraiteListe ,String> TabColDateTraites;
    @FXML private TableColumn<FactureCltTraiteListe ,String> TabColMontantTraites;
    
    @FXML private TableView<FactureCltChequeListe> TableViewListeCheques ;
    @FXML private TableColumn<FactureCltChequeListe ,String> TabColDateCheques;
    @FXML private TableColumn<FactureCltChequeListe ,String> TabColNumeroCheques;
    @FXML private TableColumn<FactureCltChequeListe ,String> TabColBanqueCheques;
    @FXML private TableColumn<FactureCltChequeListe ,String> TabColMontantCheques;
    
    @FXML public Button ButtonImprimerTraite;
    @FXML private Tab TabTypeRegement;
    
    private Service<Void> ThreadFactureCltDetail;
    
    FactureClt factureClt;
            
    public String codeFactClt;
    
    public boolean NewFacture;
    
    @Override
    public void initialize(URL url, ResourceBundle rb) {
       
        TableViewListeProduit.setEditable(false);
        
        TabColReference.setCellValueFactory(new PropertyValueFactory<ListeProduit, String>("reference"));
        TabColDesignation.setCellValueFactory(new PropertyValueFactory<ListeProduit, String>("designation"));

        TabColQuantite.setCellValueFactory(new PropertyValueFactory<ListeProduit, String>("quantite"));
        TabColQuantite.setStyle( "-fx-alignment: CENTER; -fx-font-weight:bold; -fx-font-size: 10pt;");
        TabColQuantite.getStyleClass().add("Center");

        TabColPrixHT.setCellValueFactory(new PropertyValueFactory<ListeProduit, String>("PrixHT"));
        TabColPrixHT.setStyle( "-fx-alignment: CENTER;");
        TabColPrixHT.getStyleClass().add("Center");

        TabColRemise.setCellValueFactory(new PropertyValueFactory<ListeProduit, String>("Remise"));
        TabColRemise.setStyle( "-fx-alignment: CENTER;");
        TabColRemise.getStyleClass().add("Center");

        TabColTotalHT.setCellValueFactory(new PropertyValueFactory<ListeProduit, String>("TotalHT"));
        TabColTotalHT.setStyle( "-fx-alignment: CENTER;");
        TabColTotalHT.getStyleClass().add("Center");

        TabColTVA.setCellValueFactory(new PropertyValueFactory<ListeProduit, String>("TVA"));
        TabColTVA.setStyle( "-fx-alignment: CENTER;");
        TabColTVA.getStyleClass().add("Center");

        TabColTotalTTC.setCellValueFactory(new PropertyValueFactory<ListeProduit, String>("TotalTTC"));
        TabColTotalTTC.setStyle( "-fx-alignment: CENTER; -fx-font-weight:bold; -fx-font-size: 10pt;");
        TabColTotalTTC.getStyleClass().add("Center");
        
        TabColDateTraites.setStyle( "-fx-alignment: CENTER;");
        TabColDateTraites.getStyleClass().add("Center");
        TabColDateTraites.setCellValueFactory(new PropertyValueFactory<FactureCltTraiteListe, String>("DateTraites"));
        
        TabColMontantTraites.setStyle( "-fx-alignment: CENTER;");
        TabColMontantTraites.getStyleClass().add("Center");
        TabColMontantTraites.setCellValueFactory(new PropertyValueFactory<FactureCltTraiteListe, String>("MontantTraites"));
        
        TabColDateCheques.setStyle( "-fx-alignment: CENTER;");
        TabColDateCheques.getStyleClass().add("Center");
        TabColDateCheques.setCellValueFactory(new PropertyValueFactory<FactureCltChequeListe, String>("DateCheques"));
        
        TabColNumeroCheques.setStyle( "-fx-alignment: CENTER;");
        TabColNumeroCheques.getStyleClass().add("Center");
        TabColNumeroCheques.setCellValueFactory(new PropertyValueFactory<FactureCltChequeListe, String>("NumeroCheques"));
        
        TabColBanqueCheques.setStyle( "-fx-alignment: CENTER;");
        TabColBanqueCheques.getStyleClass().add("Center");
        TabColBanqueCheques.setCellValueFactory(new PropertyValueFactory<FactureCltChequeListe, String>("BanqueCheques"));
        
        TabColMontantCheques.setStyle( "-fx-alignment: CENTER;");
        TabColMontantCheques.getStyleClass().add("Center");
        TabColMontantCheques.setCellValueFactory(new PropertyValueFactory<FactureCltChequeListe, String>("MontantCheques"));
        
        
        ButtonPrintTraite();
        
        
    } 
    
    
    @FXML
    private void FactureCltPrintButtonAction(ActionEvent event) throws IOException {
        
        PrinterJob jobPrint = PrinterJob.createPrinterJob(); 
        
        try {
            
            jobPrint.getJobSettings().setPageRanges(new PageRange(1, 1));

            if (jobPrint.showPrintDialog(null)) {
                
                FXMLLoader fxmlLoaderPrintFactureClt = new FXMLLoader(getClass().getResource("/Views/FactureClt/FactureCltPrint.fxml"));
                final Node ParentFxmlPrintFactureClt = (Node)fxmlLoaderPrintFactureClt.load();
                FactureCltPrintController PrintFactureClt = fxmlLoaderPrintFactureClt.getController();
                
                if(NewFacture){
                    PrintFactureClt.setFactureClt(factureClt, false);
                }else{
                    PrintFactureClt.setFactureClt(factureClt, true);
                }
                
                jobPrint.printPage(ParentFxmlPrintFactureClt);
                
                jobPrint.endJob();
            }
        } catch (IOException ex) {
            System.err.println("Erreur dans: Controllers.FactureClt.FactureCltDetailController.FactureCltPrintButtonAction ");
            System.err.println(ex.getMessage());
        }
    }
    
    public void SowDetailFactureClt(boolean newFacture)
    {
       ThreadFactureCltDetail = new Service<Void>(){
            @Override
            protected Task<Void> createTask(){
                return new Task<Void>(){
                    @Override
                    protected Void call() throws Exception{
                        NewFacture = newFacture;
                        FactureCltDB factureCltDB = new FactureCltDB();

                        factureClt = factureCltDB.getFactureClt(codeFactClt);

                        
                        return null;
                    }
                };
            }
	};
        
        ThreadFactureCltDetail.setOnSucceeded(new EventHandler<WorkerStateEvent>(){
            @Override
            public void handle(WorkerStateEvent event){
                CodeFactClt.setText(factureClt.getCodeFactureClt());
                DateCreation.setText(Adaptateur.NormalDateFormat(factureClt.getDateFacture()));
                Reglement.setText(factureClt.getTypeRegementString());
                TotalHorsTaxNet.setText(Adaptateur.StringToStringEspaceCurrency(factureClt.getTotalHorsTaxNet()));
                TotalTVA.setText(Adaptateur.StringToStringEspaceCurrency(factureClt.getTotalTVA()));
                TypeClt.setText(factureClt.getTypeClientString());
                NetAPayer.setText(Adaptateur.StringToStringEspaceCurrency(factureClt.getNetAPayer()));

                if(factureClt.getTypeClient()==0 ){
                     TextPrenom.setVisible(true);
                     TextMatricule.setVisible(false);

                     Nom.setText(factureClt.CltPersonne.getNom());
                     Prenom.setText(factureClt.CltPersonne.getPrenom());
                     Adresse.setText(factureClt.CltPersonne.getAdresse());
                     TELE1.setText(factureClt.CltPersonne.getTelemobileString());
                     TELE2.setText(factureClt.CltPersonne.getTelefixString());
                }

                if(factureClt.getTypeClient()==1){
                     TextPrenom.setVisible(false);
                     TextMatricule.setVisible(true);

                     Nom.setText(factureClt.CltEntreprise.getNom());
                     Prenom.setText(factureClt.CltEntreprise.getMatricule());
                     Adresse.setText(factureClt.CltEntreprise.getAdresse());
                     TELE1.setText(factureClt.CltEntreprise.getTele1String());
                     TELE2.setText(factureClt.CltEntreprise.getTele2String());
                }

                if(factureClt.getTypeClient()==2 ){
                     TextPrenom.setVisible(true);
                     TextMatricule.setVisible(false);

                     Nom.setText(factureClt.CltPassager.getNom());
                     Prenom.setText(factureClt.CltPassager.getPrenom());
                     Adresse.setText(factureClt.CltPassager.getAdresse());
                     TELE1.setText(factureClt.CltPassager.getTelefixString());
                     TELE2.setText(factureClt.CltPassager.getTelemobileString());
                }
                TableViewListeProduit.setItems(factureClt.getListeproduit());

                if(factureClt.getTypeRegementInteger() == 1)
                {
                    ValMontant.setText(Adaptateur.StringToStringEspaceCurrency(factureClt.getTotalMontantTraite()));
                    TabTypeRegement.setClosable(false);
                    TabTypeRegement.setDisable(false);
                    if(factureClt.getTypeFaciliteBoolean()){  //true Traite | false Cheque
                        TabTypeRegement.setText("Liste des traites");
                        TextMontant.setText("Total Montant Traites:");
                        TableViewListeTraites.setVisible(true);
                        //ButtonImprimerTraite.setVisible(true);
                        ObservableList<FactureCltTraiteListe> dataListe = FXCollections.observableArrayList();
                        ArrayList<TraiteClt> ListTraites = factureClt.getListeTraites();
                        for(int i=0; i<ListTraites.size(); i++)
                        {
                            dataListe.add(new FactureCltTraiteListe(ListTraites.get(i).getDateTraiteClt(), Adaptateur.StringToStringEspaceCurrency(ListTraites.get(i).getMontantTraiteClt()) ));
                        }
                        TableViewListeTraites.setItems(dataListe);
                    }else{
                        TextMontant.setText("Total Montant Cheques:");
                        TableViewListeCheques.setVisible(true);
                        TabTypeRegement.setText("Liste des Chéques");
                        ArrayList<ChequeClt> dataListCheque = factureClt.getListeCheques();
                        ObservableList<FactureCltChequeListe> dataListeCheque = FXCollections.observableArrayList();
                        for(int i=0; i<dataListCheque.size(); i++){
                            dataListeCheque.add(new FactureCltChequeListe(dataListCheque.get(i).getDatePaiement(),dataListCheque.get(i).getNumeroChequeClt(),dataListCheque.get(i).getBanqueChequeClt(),dataListCheque.get(i).getMontantChequeClt()));
                        }
                        TableViewListeCheques.setItems(dataListeCheque);
                    }
                }
                AnchorPaneLoading.setVisible(false);
                AnchorPaneDetailFactureClt.setVisible(true);
                
            }
        });
        ThreadFactureCltDetail.start();
      
    }
    
    
    
    public void ButtonPrintTraite()
    {
        ButtonImprimerTraite.setOnAction(new EventHandler<ActionEvent>() {
            @Override 
            public void handle(ActionEvent e) {
                ArrayList<TraiteClt> ListTraites = factureClt.getListeTraites();
                String strCIN= "";
                String strNomComplet = "";
                
                if(factureClt.getTypeClient() == 0){
                   strCIN =  factureClt.getCltPersonne().getCinString();
                   strNomComplet = factureClt.getCltPersonne().getNomcomplet();
                }else if(factureClt.getTypeClient() == 1){
                   strCIN =  factureClt.getCltEntreprise().getMatricule();
                   strNomComplet = factureClt.getCltEntreprise().getNom();
                }
                    
                FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/Views/TraiteClt/TraiteCltPrint.fxml"));
                try {
                    Parent FxmlPrintTraite = (Parent)fxmlLoader.load();
                    TraiteCltPrintController TraiteCltPrint = fxmlLoader.getController();
                    
                    PrinterJob jobPrint = PrinterJob.createPrinterJob();
                    
                    Printer printer = Printer.getDefaultPrinter();
                    PageLayout pageLayout = printer.createPageLayout(Paper.NA_LETTER,PageOrientation.PORTRAIT, 0, 0, 0, 0);
                    JobSettings jobSettings = jobPrint.getJobSettings();
                    jobSettings.setPageLayout(pageLayout);
                    
                    jobPrint.getJobSettings().setPageRanges(new PageRange(1, ListTraites.size()));
                    if (jobPrint.showPrintDialog(null)) 
                    {
                        for(int i=0; i<ListTraites.size(); i++)
                        {
                            TraiteCltPrint.SetData(Adaptateur.ChiffreToLettre(new BigDecimal(ListTraites.get(i).getMontantTraiteClt())), 
                                                Adaptateur.StringToStringEspaceCurrency(ListTraites.get(i).getMontantTraiteClt()), 
                                                ListTraites.get(i).getDateTraiteClt(), 
                                                strNomComplet, 
                                                strCIN);
                            jobPrint.printPage(FxmlPrintTraite);
                        }
                    }
                    jobPrint.endJob();
                    
                } catch (IOException ex) {
                    logger.error("FactureCltDetailController  : TraiteCltPrint.fxml :" + ex.getMessage());
                }
            
            }
        });
    }
    

    
}
