package Controllers.DevisClt;

import Controllers.Traitement.Adaptateur;
import Controllers.Traitement.ParametreSystem;
import Models.DevisClt.Devis;
import Models.Produit.ListeProduit;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Control;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.text.Text;
import javafx.util.Callback;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

/**
 * FXML Controller class
 * @author Maher Ben Tili
 */
public class DevisCltPrintController implements Initializable {
    
    @FXML public ImageView ImageViewLogo;
    
    @FXML private Text TextSteNom1;
    @FXML private Text TextReference;
    @FXML private Text TextDate;
    @FXML private Text TextEcheance;
    @FXML private Text TextClient;
    
    @FXML private Text TextNumDevie;
    @FXML private Text TextTotalHT;
    @FXML private Text TextTVA;
    @FXML private Text TextTotalTTC;
    
    @FXML private Text TextSteNom2;
    @FXML private Text TextSteContact;
    @FXML private Text TextSteSIREN;
    
    
    @FXML private TableView<ListProdDevis> TableViewProdDevis ;
    @FXML private TableColumn<ListProdDevis ,String> TabColDevisReference;
    @FXML private TableColumn<ListProdDevis ,String> TabColDevisDesignation;
    @FXML private TableColumn<ListProdDevis ,String> TabColDevisQuantite ;
    @FXML private TableColumn<ListProdDevis ,String> TabColDevisPrix;
    @FXML private TableColumn<ListProdDevis ,String> TabColDevisMontant;
   
    
    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        
        setImageLogo();
        
        TabColDevisReference.setCellValueFactory(new PropertyValueFactory<ListProdDevis, String>("Reference"));
        
        TabColDevisDesignation.setCellValueFactory(new PropertyValueFactory<ListProdDevis, String>("Description"));
        TabColDevisDesignation.setCellFactory(new Callback<TableColumn<ListProdDevis, String>,TableCell<ListProdDevis, String>>(){        
            @Override
            public TableCell<ListProdDevis, String> call(TableColumn<ListProdDevis, String> param) {                
                TableCell<ListProdDevis, String> cell = new TableCell<ListProdDevis, String>(){
                    @Override
                    public void updateItem(String item, boolean empty) {
                        if (item == null) {
                            super.setText(null);
                            super.setGraphic(null);
                        } else {
                            String newItem = item.trim().toLowerCase();
                            Text text = new Text(newItem);
                            super.setPrefHeight(Control.USE_COMPUTED_SIZE);
                            text.wrappingWidthProperty().bind(super.widthProperty());
                            super.setGraphic(text);
                        }
                    }
                };  
                return cell;
            }
        });
        
        
        TabColDevisQuantite.setCellValueFactory(new PropertyValueFactory<ListProdDevis, String>("Quantite"));
        TabColDevisQuantite.setStyle( "-fx-alignment: CENTER;");
        TabColDevisQuantite.getStyleClass().add("Center");

        TabColDevisPrix.setCellValueFactory(new PropertyValueFactory<ListProdDevis, String>("Prix"));
        TabColDevisPrix.setStyle( "-fx-alignment: CENTER;");
        TabColDevisPrix.getStyleClass().add("Center");

        TabColDevisMontant.setCellValueFactory(new PropertyValueFactory<ListProdDevis, String>("Montant"));
        TabColDevisMontant.setStyle( "-fx-alignment: CENTER;");
        TabColDevisMontant.getStyleClass().add("Center");

        
        TextSteNom1.setText(ParametreSystem.CompanyName);
        TextSteNom2.setText("Ste:"+ParametreSystem.CompanyName+" | Adress:"+ParametreSystem.CompanyAddress+" | Tele: "+ParametreSystem.CompanyTele);
        TextSteContact.setText("Fax:"+ParametreSystem.CompanyFax+" | Mail:"+ParametreSystem.CompanyMail+" | Site:"+ParametreSystem.CompanySite);
        TextSteSIREN.setText(ParametreSystem.CompanySIREN);
    }    
    
    public void SetDevis(Devis devis)
    {
        TextNumDevie.setText(devis.getCodeDevis());
        TextReference.setText(devis.getCodeDevis());
        TextDate.setText(Adaptateur.NormalDateFormat(devis.getDateCreation()));
        TextEcheance.setText(devis.getValidite());
        
        if(devis.getTypeClient()==0){
            TextClient.setText(devis.getCodeClient()+" - "+devis.getClient().getNom()+" - "+devis.getClient().getPrenom());
        }else if(devis.getTypeClient()==1){
            TextClient.setText(devis.getCodeClient()+" - "+devis.getEntreprise().getNom()+" - "+devis.getEntreprise().getMatricule());
        }
        else if(devis.getTypeClient()==2){
            TextClient.setText(devis.getCodeClient()+" - "+devis.getPassager().getNom()+" - "+devis.getPassager().getPrenom());              
        }
        ObservableList<ListProdDevis> PodDevis = FXCollections.observableArrayList();
        
        for(ListeProduit liste : devis.getListeproduit())
        {
            if(!liste.getReference().equals(""))
            {
                float remise = Adaptateur.ArrondStringToFloat(liste.getRemise().replace("%", "")) ;
                float prixht = Adaptateur.ArrondStringToFloat(liste.getPrixHT()) ;
                float tva = Adaptateur.StringToFloat(liste.getTVA().replace("%", "")) ;
                float qte = Adaptateur.StringToFloat(liste.getQuantite()) ;
                
                float totalht = (prixht - ((prixht * remise)/100)) ;
                float prixttc = totalht + ((totalht * tva)/100) ;
                
                float montant = prixttc * qte;
                
                PodDevis.add(new ListProdDevis(liste.getReference(), liste.getDesignation(), liste.getQuantite(), Adaptateur.FloatToStringEspace(prixttc), Adaptateur.FloatToStringEspace(montant)));
            }
        }
        
        TextTVA.setText(Adaptateur.StringToStringEspaceCurrency(devis.getTotalTVA()));
        TextTotalHT.setText(Adaptateur.StringToStringEspaceCurrency(devis.getTotalHorsTaxNet()));
        TextTotalTTC.setText(Adaptateur.StringToStringEspaceCurrency(devis.getNetAPayer()));
        
        TableViewProdDevis.setItems(PodDevis);
    }
    
    private void setImageLogo()
    {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            // optional, but recommended
            // process XML securely, avoid attacks like XML External Entities (XXE)
            dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);

            // parse XML file
            DocumentBuilder db = dbf.newDocumentBuilder();

            //PowerERP\conf\logo.xml
            Document doc = db.parse(new File("./conf/logo.xml"));

            doc.getDocumentElement().normalize();

            Element elementCNX  = (Element) doc.getElementsByTagName("DevisCltPrint").item(0);
            
            String pathLogo = elementCNX.getElementsByTagName("PathImage").item(0).getTextContent();
            FileInputStream fis = new FileInputStream(pathLogo);
            ImageViewLogo.setImage(new Image(fis));
            
            ImageViewLogo.setFitWidth(Double.parseDouble(elementCNX.getElementsByTagName("FitWidth").item(0).getTextContent()));
            ImageViewLogo.setFitHeight(Double.parseDouble(elementCNX.getElementsByTagName("FitHeight").item(0).getTextContent()));
            ImageViewLogo.setLayoutX(Double.parseDouble(elementCNX.getElementsByTagName("LayoutX").item(0).getTextContent()));
            ImageViewLogo.setLayoutY(Double.parseDouble(elementCNX.getElementsByTagName("LayoutY").item(0).getTextContent()));
        } 
        catch (ParserConfigurationException | SAXException | IOException e) {
            System.out.println("error AuthentificationController/setImageLogo "+e.getMessage());
        }
    }
    
    public static class ListProdDevis {
        
        private final SimpleStringProperty Reference;
        private final SimpleStringProperty Description;
        private final SimpleStringProperty Quantite;
        private final SimpleStringProperty Prix;
        private final SimpleStringProperty Montant;
        
        private ListProdDevis(String reference, String description, String quantite, String prix, String montant) {
            this.Reference = new SimpleStringProperty(reference);
            this.Description = new SimpleStringProperty(description);
            this.Quantite = new SimpleStringProperty(quantite);
            this.Prix = new SimpleStringProperty(prix);
            this.Montant = new SimpleStringProperty(montant);
        }
        
        public String getReference() {
            return Reference.get();
        }
 
        public void setReference(String reference) {
            Reference.set(reference);
        }
        
        public String getDescription() {
            return Description.get();
        }
 
        public void setDescription(String description) {
            Description.set(description);
        }
 
        public String getQuantite() {
            return Quantite.get();
        }
 
        public void setQuantite(String quantite) {
            Quantite.set(quantite);
        }
        
        public String getPrix() {
            return Prix.get();
        }
 
        public void setPrix(String prix) {
            Prix.set(prix);
        }
        
        public String getMontant() {
            return Montant.get();
        }
 
        public void setMontant(String montant) {
            Montant.set(montant);
        }
    }
}
