/*
 * DlgGenPesPjs.java
 *
 * Created on 8 janvier 2008, 15:51
 */
package fr.gouv.finances.cp.xemelios.plugin.generatorPesPjs;

import fr.gouv.finances.cp.utils.Base64;
import fr.gouv.finances.cp.xemelios.utils.TextWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.GZIPOutputStream;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.xerces.parsers.DOMParser;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;


/**
 *
 * @author  jp.tessier
 */
public class DlgGenPesPjs extends javax.swing.JDialog {

    private JFrame parentWindow;
    private TableModelPJ tableModel = new TableModelPJ();
    private String NAMESPACE_PES_ALLER = "http://www.minefi.gouv.fr/cp/helios/pes_v2/Rev0/aller";
    private String NAMESPACE_PES_ALLER_COMMUN = "http://www.minefi.gouv.fr/cp/helios/pes_v2/commun";
    /** Creates new form DlgGenPesPjs */
    public DlgGenPesPjs(javax.swing.JFrame parent, boolean modal) {
        super(parent, modal);
        parentWindow = parent;
        initComponents();

        /* My initialisations */
        initComportement();
        initTextFields();
        setLocationRelativeTo(parent);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        onglets = new javax.swing.JTabbedPane();
        PanelGeneral = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        fileToGenerate = new javax.swing.JTextField();
        idPost = new javax.swing.JTextField();
        idColl = new javax.swing.JTextField();
        finess = new javax.swing.JTextField();
        codColl = new javax.swing.JTextField();
        codBudg = new javax.swing.JTextField();
        libCollBudg = new javax.swing.JTextField();
        PanelPieces = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablePjs = new javax.swing.JTable();
        AddPJ = new javax.swing.JButton();
        editPJ = new javax.swing.JButton();
        deletePJ = new javax.swing.JButton();
        close_button = new javax.swing.JButton();
        save_button = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        onglets.setMaximumSize(new java.awt.Dimension(1024, 768));
        onglets.setMinimumSize(new java.awt.Dimension(300, 300));

        jLabel1.setText("Fichier à générer");

        jLabel2.setText("Identifiant du poste");

        jLabel3.setText("Identifiant Collectivité");

        jLabel4.setText("Finess Juridique");

        jLabel5.setText("Code Collectivité");

        jLabel6.setText("Code Budget");

        jLabel7.setText("Libellé Collectivité Budget");

        fileToGenerate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fileToGenerateActionPerformed(evt);
            }
        });
        fileToGenerate.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                fileToGenerateFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                fileToGenerateFocusLost(evt);
            }
        });

        idPost.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                idPostFocusLost(evt);
            }
        });

        codColl.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                codCollFocusLost(evt);
            }
        });

        codBudg.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                codBudgFocusLost(evt);
            }
        });

        org.jdesktop.layout.GroupLayout PanelGeneralLayout = new org.jdesktop.layout.GroupLayout(PanelGeneral);
        PanelGeneral.setLayout(PanelGeneralLayout);
        PanelGeneralLayout.setHorizontalGroup(
            PanelGeneralLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(PanelGeneralLayout.createSequentialGroup()
                .add(30, 30, 30)
                .add(PanelGeneralLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(jLabel7)
                    .add(jLabel2)
                    .add(jLabel3)
                    .add(jLabel4)
                    .add(jLabel5)
                    .add(jLabel6)
                    .add(jLabel1))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(PanelGeneralLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(fileToGenerate, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 335, Short.MAX_VALUE)
                    .add(idPost, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 335, Short.MAX_VALUE)
                    .add(idColl, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 335, Short.MAX_VALUE)
                    .add(finess, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 335, Short.MAX_VALUE)
                    .add(codColl, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 335, Short.MAX_VALUE)
                    .add(codBudg, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 335, Short.MAX_VALUE)
                    .add(libCollBudg, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 335, Short.MAX_VALUE))
                .addContainerGap())
        );
        PanelGeneralLayout.setVerticalGroup(
            PanelGeneralLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(PanelGeneralLayout.createSequentialGroup()
                .add(27, 27, 27)
                .add(PanelGeneralLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(fileToGenerate, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel1))
                .add(12, 12, 12)
                .add(PanelGeneralLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel2)
                    .add(idPost, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(18, 18, 18)
                .add(PanelGeneralLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel3)
                    .add(idColl, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(18, 18, 18)
                .add(PanelGeneralLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel4)
                    .add(finess, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(18, 18, 18)
                .add(PanelGeneralLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel5)
                    .add(codColl, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(18, 18, 18)
                .add(PanelGeneralLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel6)
                    .add(codBudg, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(18, 18, 18)
                .add(PanelGeneralLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel7)
                    .add(libCollBudg, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(35, Short.MAX_VALUE))
        );

        onglets.addTab("Généralités", PanelGeneral);

        tablePjs.setModel(tableModel);
        jScrollPane1.setViewportView(tablePjs);

        AddPJ.setText("Ajouter");
        AddPJ.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AddPJActionPerformed(evt);
            }
        });

        editPJ.setText("Editer");
        editPJ.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editPJActionPerformed(evt);
            }
        });

        deletePJ.setText("Supprimer");
        deletePJ.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deletePJActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout PanelPiecesLayout = new org.jdesktop.layout.GroupLayout(PanelPieces);
        PanelPieces.setLayout(PanelPiecesLayout);
        PanelPiecesLayout.setHorizontalGroup(
            PanelPiecesLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(PanelPiecesLayout.createSequentialGroup()
                .addContainerGap()
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 361, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(18, 18, 18)
                .add(PanelPiecesLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(deletePJ, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 101, Short.MAX_VALUE)
                    .add(editPJ, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 101, Short.MAX_VALUE)
                    .add(AddPJ, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 101, Short.MAX_VALUE))
                .addContainerGap())
        );
        PanelPiecesLayout.setVerticalGroup(
            PanelPiecesLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, PanelPiecesLayout.createSequentialGroup()
                .addContainerGap(43, Short.MAX_VALUE)
                .add(PanelPiecesLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, PanelPiecesLayout.createSequentialGroup()
                        .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 221, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(33, 33, 33))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, PanelPiecesLayout.createSequentialGroup()
                        .add(AddPJ)
                        .add(27, 27, 27)
                        .add(editPJ)
                        .add(27, 27, 27)
                        .add(deletePJ)
                        .add(103, 103, 103))))
        );

        onglets.addTab("Pièces Justificatives", PanelPieces);

        close_button.setText("Fermer");
        close_button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                close_buttonActionPerformed(evt);
            }
        });

        save_button.setText("Enregistrer");
        save_button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                save_buttonActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 525, Short.MAX_VALUE)
            .add(layout.createSequentialGroup()
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(onglets, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(close_button)
                        .add(18, 18, 18)
                        .add(save_button)
                        .add(14, 14, 14))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 376, Short.MAX_VALUE)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(onglets, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(save_button)
                    .add(close_button))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private void fileToGenerateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileToGenerateActionPerformed
        
}//GEN-LAST:event_fileToGenerateActionPerformed

    private void fileToGenerateFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_fileToGenerateFocusLost
        doCheck();
    }//GEN-LAST:event_fileToGenerateFocusLost

    private void idPostFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_idPostFocusLost
        doCheck();
    }//GEN-LAST:event_idPostFocusLost

    private void codCollFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_codCollFocusLost
        doCheck();
    }//GEN-LAST:event_codCollFocusLost

    private void codBudgFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_codBudgFocusLost
        doCheck();
    }//GEN-LAST:event_codBudgFocusLost

    private void close_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_close_buttonActionPerformed
        setVisible(false);
}//GEN-LAST:event_close_buttonActionPerformed

    private void AddPJActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddPJActionPerformed
        DlgMakePJ makePj = new DlgMakePJ(parentWindow, true);
        makePj.setIdCollIdPostCodBud(idColl.getText(),idPost.getText(),codColl.getText(),codBudg.getText());
        if(makePj.run()) {
            tableModel.add(makePj.getPiece_justificative());
        }
    }//GEN-LAST:event_AddPJActionPerformed

    private void editPJActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editPJActionPerformed
        DlgMakePJ dlgMakePJ = new DlgMakePJ(parentWindow,true);
        int rowSeleted = tablePjs.getSelectedRow();
        if(dlgMakePJ.runEdit(tableModel.getData(rowSeleted))) {
            tableModel.refresh();
        }
}//GEN-LAST:event_editPJActionPerformed

    private void deletePJActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deletePJActionPerformed
        tableModel.remove(tablePjs.getSelectedRow());
    }//GEN-LAST:event_deletePJActionPerformed

    private void fileToGenerateFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_fileToGenerateFocusGained
        onglets.setEnabled(true);
    }//GEN-LAST:event_fileToGenerateFocusGained

    private void save_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_save_buttonActionPerformed
        if(formIsValid()){
            JFileChooser fc = new JFileChooser();
            fc.setSelectedFile(new File(new File(System.getProperty("user.home")),fileToGenerate.getText()+".xml"));
            fc.addChoosableFileFilter(new FileFilter() {
                public boolean accept(File f) {
                    return f.isDirectory() || f.getName().toUpperCase().endsWith("XML");
                }
                public String getDescription() {
                    return "Fichiers XML";
                }
            });
                 
        int reponse = fc.showSaveDialog(this);
        
        if(reponse==JFileChooser.APPROVE_OPTION) {
            startVentilateur();
            setPropertiesGeneratorPESPJs();
            Document doc = createDOMdoc();
            
            TextWriter tw = new TextWriter(doc,"ISO-8859-1");
            tw.setPrettyPrint(true);

            try{
                tw.write(new FileOutputStream(new File(fc.getSelectedFile().getAbsolutePath())));
            } catch (IOException ex) {
                Logger.getLogger(DlgGenPesPjs.class.getName()).log(Level.SEVERE, null, ex);
            }
            
            stopVentilateur();
            JOptionPane.showMessageDialog(parentWindow,"Le flux PES PJ à bien été généré.","Confirmation de la création du flux PES PJ",JOptionPane.INFORMATION_MESSAGE);
            
            resetDialog();
        }        
            
        }
}//GEN-LAST:event_save_buttonActionPerformed
    
    private void setPropertiesGeneratorPESPJs(){
        FileOutputStream fos = null;
        try {
            File f = new File(System.getProperty("user.home"),"xemelios-PJ-generator.properties");
            System.out.println("fichier de proprietes dans : "+f.getAbsolutePath());
           
            Properties props = new Properties();

            if(f.exists()){
                FileInputStream fis = new FileInputStream(f);
                props.load(fis);
                fis.close();
            }
            
            fos = new FileOutputStream(f);
                
            props.setProperty("idpost", idPost.getText());
            props.setProperty("idcoll", idColl.getText());
            props.setProperty("finess", finess.getText());
            props.setProperty("codcoll", codColl.getText());
            props.setProperty("codbudg", codBudg.getText());
            props.setProperty("libcodbudg", libCollBudg.getText());
            
            props.store(fos,"");
            
            fos.flush();
            fos.close();

        } catch (IOException ex) {
            Logger.getLogger(DlgGenPesPjs.class.getName()).log(Level.SEVERE, null, ex);
        }
    }   
    
    private void resetDialog(){
        for(int i=0;i<tableModel.getRowCount();i++){
                tableModel.remove(i);
        }
        onglets.setSelectedIndex(0);
        fileToGenerate.setText("");
        onglets.setEnabled(false);
        doCheck();
    }
    
    private Document createDOMdoc() {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.newDocument();

            Element root = doc.createElementNS(NAMESPACE_PES_ALLER,"PES_Aller");
            root.setAttribute("xmlns",NAMESPACE_PES_ALLER);
            root.setAttribute("xmlns:ds","http://www.w3.org/2000/09/xmldsig#");
            root.setAttribute("xmlns:xad","http://uri.etsi.org/01903/v1.1.1#");
            root.setAttribute("xmlns:cm",NAMESPACE_PES_ALLER_COMMUN);
            
            doc.appendChild(root);

            createEnveloppe(doc);
            createEntetePES(doc);
            if(tableModel.getRowCount()>0){
                createPES_PJ(doc);
            }
                
            return doc;

        } catch (ParserConfigurationException ex) {
            Logger.getLogger(DlgGenPesPjs.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
    
    private void createEnveloppe(Document doc){
        Element enveloppe = doc.createElementNS(NAMESPACE_PES_ALLER,"Enveloppe");
        
        Element parametre = doc.createElementNS(NAMESPACE_PES_ALLER,"Parametres");
        
        Element version = doc.createElementNS(NAMESPACE_PES_ALLER,"Version");
        version.setAttribute("V","01");
        
        Element typeFic = doc.createElementNS(NAMESPACE_PES_ALLER,"TypFic");
        typeFic.setAttribute("V","PES_PJ");
        
        Element nomFic = doc.createElementNS(NAMESPACE_PES_ALLER,"NomFic");
        nomFic.setAttribute("V",fileToGenerate.getText());
        
        parametre.appendChild(version);
        parametre.appendChild(typeFic);
        parametre.appendChild(nomFic);
        
        enveloppe.appendChild(parametre);
        
        doc.getChildNodes().item(0).appendChild(enveloppe);
    }
    
    private void createEntetePES(Document doc){
        Element entetePES = doc.createElementNS(NAMESPACE_PES_ALLER,"EntetePES");
        
        Element dteStr = doc.createElementNS(NAMESPACE_PES_ALLER,"DteStr");
        dteStr.setAttribute("V",new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        
        Element idPoste = doc.createElementNS(NAMESPACE_PES_ALLER,"IdPost");
        idPoste.setAttribute("V",idPost.getText());
        
        Element idCollec = doc.createElementNS(NAMESPACE_PES_ALLER,"IdColl");
        idCollec.setAttribute("V",idColl.getText());
        
        Element finJur = doc.createElementNS(NAMESPACE_PES_ALLER,"FinJur");
        finJur.setAttribute("V",finess.getText());
        
        Element codCollec = doc.createElementNS(NAMESPACE_PES_ALLER,"CodCol");
        codCollec.setAttribute("V",codColl.getText());
        
        Element codBud = doc.createElementNS(NAMESPACE_PES_ALLER,"CodBud");
        codBud.setAttribute("V",codBudg.getText());
        
        Element libelleColBud = doc.createElementNS(NAMESPACE_PES_ALLER,"LibelleColBud");
        libelleColBud.setAttribute("V",libCollBudg.getText());
        
        entetePES.appendChild(dteStr);
        entetePES.appendChild(idPoste);
        entetePES.appendChild(idCollec);
        entetePES.appendChild(finJur);
        entetePES.appendChild(codCollec);
        entetePES.appendChild(codBud);
        entetePES.appendChild(libelleColBud);
        
        doc.getChildNodes().item(0).appendChild(entetePES);
    }
    
    private void createPES_PJ(Document doc){
        try {
            Element PES_PJ = doc.createElementNS(NAMESPACE_PES_ALLER,"PES_PJ");
            
            Element entetePES_PJ = doc.createElementNS(NAMESPACE_PES_ALLER,"EnTetePES_PJ");
            Element idVer = doc.createElementNS(NAMESPACE_PES_ALLER,"IdVer");
            idVer.setAttribute("V", "1");
            entetePES_PJ.appendChild(idVer);

            PES_PJ.appendChild(entetePES_PJ);

            createPJs(doc,PES_PJ);

            doc.getChildNodes().item(0).appendChild(PES_PJ);
        } catch (IOException ex) {
            Logger.getLogger(DlgGenPesPjs.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    private void createPJs(Document doc,Element pes_pj) throws IOException{
        Vector<Element> vpce = new Vector<Element>();
        Element contenu;
        
        for(int i = 0;i<tableModel.getRowCount();i++){
            PJ pj = tableModel.getData(i);
            contenu = doc.createElementNS(NAMESPACE_PES_ALLER,"Contenu");
            Element pce = doc.createElementNS(NAMESPACE_PES_ALLER,"PJ");
            
            // Si ce n'est pas une facture, compression de la pj et encodage en base64 de son contenu
            if (!(pj.getTypePJ().contains("Facture"))) {
                
                Element fichier = doc.createElementNS(NAMESPACE_PES_ALLER,"Fichier");
                
                // Creation d'un inputStream sur la PJ
                FileInputStream fis = new FileInputStream(pj.getPjFile());
                
                // Creation du gzip et d'un outputStream
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                GZIPOutputStream gzo = new GZIPOutputStream(baos);
                
                // Lecture de la PJ et remplissage du gzip
                byte[] bTmp = new byte[2048];
                int read = 0;
                do {
                    read = fis.read(bTmp);
                    if (read > 0) {
                        gzo.write(bTmp, 0, read);
                    }
                } while (read > 0);

                fis.close();
                gzo.finish();
                gzo.flush();
                gzo.close();
                
                //System.out.println(Base64.encodeBytes(baos.toByteArray(),true));
                Text txt = doc.createTextNode(Base64.encodeBytes(baos.toByteArray(),true));
                fichier.appendChild(txt);
                
                baos.close();
                
                contenu.appendChild(fichier);
                pce.appendChild(contenu);
                
            } else {
                try {
                    // Creation d'un InputStream pour lire la PJ
                    FileInputStream fis = new FileInputStream(pj.getPjFile());
                   
                    // Parssage de la PJ
                    DOMParser domp = new DOMParser();
                    domp.parse(new InputSource(fis));
                    
                    Node node = doc.adoptNode(domp.getDocument().getDocumentElement());
                    
                    // Ajout de la PJ
                    contenu.appendChild(node);
                    pce.appendChild(contenu);
                    
                } catch (SAXException ex) {
                    Logger.getLogger(DlgGenPesPjs.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
            // Creation des éléments fils de la PES_PJ
            Element idUnique = doc.createElementNS(NAMESPACE_PES_ALLER,"IdUnique");
            idUnique.setAttribute("V",pj.getIdentifiant());
            
            Element nomPJ = doc.createElementNS(NAMESPACE_PES_ALLER,"NomPJ");
            nomPJ.setAttribute("V",pj.getNamePJ());
            
            Element typePJ = doc.createElementNS(NAMESPACE_PES_ALLER,"TypePJ");
            typePJ.setAttribute("V",pj.getTypePJ().split(" - ")[0]);
            
            Element desc = doc.createElementNS(NAMESPACE_PES_ALLER,"Description");
            desc.setAttribute("V",pj.getDescription());
            
            pce.appendChild(idUnique);
            pce.appendChild(nomPJ);
            pce.appendChild(typePJ);
            pce.appendChild(desc);
            
            createRefsComptas(doc,pj,pce);
            
            vpce.add(pce);
        }
        for(Element e:vpce){
            pes_pj.appendChild(e);
        }
    }
    
    private void createRefsComptas(Document doc,PJ pj,Element pce){
        for(RefCompta rc:pj.getVRefsComptas()){
            Element refCompta = doc.createElementNS(NAMESPACE_PES_ALLER,"RefCompta");
            
            Element domaine = doc.createElementNS(NAMESPACE_PES_ALLER,"Domaine");
            domaine.setAttribute("V",rc.getDomaine());
            
            Element exer = doc.createElementNS(NAMESPACE_PES_ALLER,"Exercice");
            exer.setAttribute("V",rc.getExercice().toString());
            
            Element typObj = doc.createElementNS(NAMESPACE_PES_ALLER,"TypeObjet");
            typObj.setAttribute("V",rc.getTypePiece().key);
            
            Element id = doc.createElementNS(NAMESPACE_PES_ALLER,"Identifiant");
            id.setAttribute("V",rc.getNumPiece().toString());
            
            Element complId = doc.createElementNS(NAMESPACE_PES_ALLER,"ComplementIdentifiant");
            complId.setAttribute("V",rc.getNumLignePiece().toString());
            
            Element codProd = doc.createElementNS(NAMESPACE_PES_ALLER,"CodProd");
            codProd.setAttribute("V",rc.getCodeProduit());
            
            Element idTiers = doc.createElementNS(NAMESPACE_PES_ALLER,"IdTiers");
            idTiers.setAttribute("V",rc.getIdTiers());
            
            refCompta.appendChild(domaine);
            refCompta.appendChild(exer);
            refCompta.appendChild(typObj);
            refCompta.appendChild(id);
            refCompta.appendChild(complId);
            refCompta.appendChild(codProd);
            refCompta.appendChild(idTiers);
            
            pce.appendChild(refCompta);
        }
    }
    
    private void initTextFields() {
        String configFileName = System.getProperty("user.home");
        
        File f = new File(configFileName,"xemelios-PJ-generator.properties");
            
        if(f.exists()){
            Properties props = new Properties();
            System.out.println("in initTextFields()");
            try {
                props.load(new FileInputStream(f));
                
                idPost.setText(props.getProperty("idpost"));
                idColl.setText(props.getProperty("idcoll"));
                finess.setText(props.getProperty("finess"));
                codColl.setText(props.getProperty("codcoll"));
                codBudg.setText(props.getProperty("codbudg"));
                libCollBudg.setText(props.getProperty("libcollbudg"));
            } catch (FileNotFoundException ex) {
                System.out.println("Fichier " + configFileName + " introuvable!");
            } catch (IOException ex) {
                ex.getMessage();
            }
        }
        
        doCheck();
    }

    private void initComportement() {
        onglets.setEnabled(false);
    }
    
    private void doCheck(){
        if (fileToGenerate.getText().length() > 0 && idPost.getText().length() > 0 && codColl.getText().length() > 0 && codBudg.getText().length() > 0) {
           onglets.setEnabled(true);
        } else {
           onglets.setEnabled(false);
        }
    }
    
    private boolean formIsValid() {
        System.out.println("in formIsValid()");
        if (fileToGenerate.getText().length() > 0 && idPost.getText().length() > 0 && codColl.getText().length() > 0 && codBudg.getText().length() > 0) {
            return true;
        } else {
            JOptionPane.showMessageDialog(this,
                "Une erreur de saisie c'est produite.\n\n" +
                "L'une des informations suivante est absente : \n" +
                "- Le nom du fichier.\n" +
                "- L'identifiant du poste.\n" +
                "- Le code de la collectivité." +
                "- Le code du budget.",
                "Erreur de saisie d'informations",JOptionPane.ERROR_MESSAGE);
            return false;
        }
    }

    public void stopVentilateur() {
        getGlassPane().setVisible(false);
    }
    
    public void startVentilateur() {
        getGlassPane().setVisible(true);
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                DlgGenPesPjs dialog = new DlgGenPesPjs(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton AddPJ;
    private javax.swing.JPanel PanelGeneral;
    private javax.swing.JPanel PanelPieces;
    private javax.swing.JButton close_button;
    private javax.swing.JTextField codBudg;
    private javax.swing.JTextField codColl;
    private javax.swing.JButton deletePJ;
    private javax.swing.JButton editPJ;
    private javax.swing.JTextField fileToGenerate;
    private javax.swing.JTextField finess;
    private javax.swing.JTextField idColl;
    private javax.swing.JTextField idPost;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField libCollBudg;
    private javax.swing.JTabbedPane onglets;
    private javax.swing.JButton save_button;
    private javax.swing.JTable tablePjs;
    // End of variables declaration//GEN-END:variables
}
