package Controllers.FactureClt;

import Controllers.Traitement.Adaptateur;
import Controllers.Traitement.ParametreSystem;
import Models.Client.Client;
import Models.Client.ClientEntreprise;
import Models.Client.ClientPassager;
import Models.FactureClt.FactureClt;
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.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.print.PageRange;
import javafx.print.PrinterJob;
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.control.cell.TextFieldTableCell;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
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 FactureCltPrintController implements Initializable {

    @FXML private AnchorPane AnchorPaneTotal;
    
    @FXML public ImageView ImageViewLogo;
    
    @FXML private Text TextSteNom;
    @FXML private Text TextSteAdress;
    @FXML private Text TextSteTeleFax;
    @FXML private Text TextSteIFCR;
    @FXML private Text TextSteRIB;
    @FXML private Text TextSteEmailSite;
    
    @FXML private Text TextNumFacture;
    @FXML private Text TextDateFacture;
    @FXML private Text TextNumCommande;
    @FXML private Text TextPagination;
    
    @FXML private Text TextCltNomPrenom;
    @FXML private Text TextCltTele;
    @FXML private Text TextCltAdress;
    
    @FXML private Text TextDuplicata;
    
    @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 Text TextTotalRemise;
    @FXML private Text TextTotalHT;
    @FXML private Text TextTotalTVA;                
    @FXML private Text TextTimbre;              
    @FXML private Text TextNetPayer;  

    
    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        
        setImageLogo();
        
        TextSteNom.setText(ParametreSystem.CompanyName);
        TextSteAdress.setText(ParametreSystem.CompanyAddress);
        TextSteTeleFax.setText(ParametreSystem.CompanyTele+" |  Fax: "+ParametreSystem.CompanyFax);
        TextSteIFCR.setText(ParametreSystem.CompanyIF+" |  M.F: "+ParametreSystem.CompanyMF);
        TextSteRIB.setText(ParametreSystem.RIB);
        TextSteEmailSite.setText(ParametreSystem.CompanyMail+" | Site:"+ParametreSystem.CompanySite);
    
    
        TabColReference.setCellValueFactory(new PropertyValueFactory<ListeProduit, String>("reference"));
        TabColReference.setStyle( "-fx-alignment: CENTER;");
        TabColReference.getStyleClass().add("Center");
        
        TabColDesignation.setCellValueFactory(new PropertyValueFactory<ListeProduit, String>("designation"));
        TabColDesignation.setCellFactory(new Callback<TableColumn<ListeProduit,String>,TableCell<ListeProduit,String>>(){        
            @Override
            public TableCell<ListeProduit, String> call(TableColumn<ListeProduit, String> param) {                
                TableCell<ListeProduit, String> cell = new TableCell<ListeProduit, 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;
            }
        });
        
        TabColQuantite.setCellValueFactory(new PropertyValueFactory<ListeProduit, String>("quantite"));
        TabColQuantite.setStyle( "-fx-alignment: CENTER;");
        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;");
        TabColTotalTTC.getStyleClass().add("Center");
    
        TabColReference.setCellFactory(TextFieldTableCell.<ListeProduit>forTableColumn());
        TabColQuantite.setCellFactory(TextFieldTableCell.<ListeProduit>forTableColumn());
        TabColRemise.setCellFactory(TextFieldTableCell.<ListeProduit>forTableColumn());
    }    
    
    
    public void setFactureClt(FactureClt factureClt,  boolean duplicata)
    {
        if(duplicata){
           TextDuplicata.setVisible(true); 
       }else{
           TextDuplicata.setVisible(false);
       }
        
        TableViewListeProduit.setItems(factureClt.getListeproduit());
        
        TextNumFacture.setText(factureClt.getCodeFactureClt());
        TextDateFacture.setText(Adaptateur.NormalDateFormat(factureClt.getDateFacture()));
        TextNumCommande.setText(factureClt.getIdCommandeClt());
        TextPagination.setText("1/1");
        
        //0 Personne  1 Entreprise 2 Passager
        if(factureClt.getTypeClient() == 0){
            Client client = factureClt.getCltPersonne();
            TextCltNomPrenom.setText(client.getNom()+" "+client.getPrenom());
            TextCltTele.setText(client.getTelefixString());
            TextCltAdress.setText(client.getAdresse());
        }else if(factureClt.getTypeClient() == 1){
            ClientEntreprise entreprise = factureClt.getCltEntreprise();
            TextCltNomPrenom.setText(entreprise.getNom());
            TextCltTele.setText(entreprise.getTele1String());
            TextCltAdress.setText(entreprise.getAdresse());
        }else if(factureClt.getTypeClient() == 2){
            ClientPassager passager = factureClt.getCltPassager();
            TextCltNomPrenom.setText(passager.getNom()+" "+passager.getPrenom());
            TextCltTele.setText(passager.getTelefixString());
            TextCltAdress.setText(passager.adresse);
        }
        
        TextTotalRemise.setText(Adaptateur.StringToStringEspace(factureClt.getRemise()));
        TextTotalHT.setText(Adaptateur.StringToStringEspace(factureClt.getTotalHorsTaxNet()));
        TextTotalTVA.setText(Adaptateur.StringToStringEspace(factureClt.getTotalTVA()));                
        TextTimbre.setText(Adaptateur.StringToStringEspace(factureClt.getTimbre()));              
        TextNetPayer.setText(Adaptateur.StringToStringEspace(factureClt.getNetAPayer()));
    
    }
    
    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("FactureCltPrint").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());
        }
    }
}
