/*
 * Copyright
 *   2007 axYus - www.axyus.com
 *   2007 N.Le Corre - nicolas.lecorre@axyus.com
 *
 * This file is part of XEMELIOS.
 *
 * XEMELIOS is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * XEMELIOS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with XEMELIOS; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package fr.gouv.finances.cp.xemelios.ui.export;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.sql.SQLException;
import java.util.Vector;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.filechooser.FileFilter;
import javax.swing.table.AbstractTableModel;

import org.apache.log4j.Logger;

import fr.gouv.finances.dgfip.utils.Pair;
import fr.gouv.finances.cp.utils.StartUrl;
import fr.gouv.finances.cp.utils.ui.InterruptibleInfiniteGlassPane;
import fr.gouv.finances.dgfip.xemelios.common.config.DocumentModel;
import fr.gouv.finances.dgfip.xemelios.common.config.DocumentsModel;
import fr.gouv.finances.dgfip.xemelios.common.config.ElementModel;
import fr.gouv.finances.dgfip.xemelios.common.config.EtatModel;
import fr.gouv.finances.dgfip.xemelios.data.DataConfigurationException;
import fr.gouv.finances.dgfip.xemelios.data.DataLayerManager;
import fr.gouv.finances.dgfip.xemelios.data.DataResultSet;
import fr.gouv.finances.dgfip.xemelios.export.ConfigModel;
import fr.gouv.finances.cp.xemelios.export.Exporter;
import fr.gouv.finances.cp.xemelios.ui.resulttable.EtatResultTableModel;
import fr.gouv.finances.dgfip.xemelios.auth.UnauthorizedException;
import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;

/**
 *
 * @author  nicolas.lecorre
 */
public class DlgSearchConfig extends JDialog {
    private static Logger logger = Logger.getLogger(DlgSearchConfig.class);
    
    //
    private File _f = null;
    
    private DlgSearchConfig _sc = null;
    
    // la liste des documents
    private DocumentsModel docModels;
    
    // résultat de la recherche
    private Vector<ConfigModel> listeConfigs;
    
    private int mode = 0;
    // menu Fichier / Exporter
    public static final int EXEC_FROM_RECHERCHE = 1;
    // Menu Export / Config
    public static final int EXEC_FROM_CONF = 2;
    // Menu Export / Executer
    public static final int EXEC_FROM_MENU = 3;
    
    // variables pour l'export
    private EtatResultTableModel ertm;
    private DocumentModel dm;
    private ElementModel em;
    
    private Pair coll = null;
    private Pair budg = null;
    private String fic = null;
    private Pair SK1 = null;
    private Pair SK2 = null;
    private int whatToExport = 0;
    
    private InterruptibleInfiniteGlassPane interruptible;
    
    private XemeliosUser user;
    
    /** Creates new form SearchConfigs */
    public DlgSearchConfig(JFrame parent,DocumentsModel dm, int mode, XemeliosUser user) {
        super(parent, true);
        _sc = this;
        this.user=user;
        docModels = dm;
        setMode(mode);
//logger.debug("mode is "+mode);
        initComponents();
        
    }
    
    private void activateSupModButtons(boolean active) {
        bSupprimer.setEnabled(active);
        bChanger.setEnabled(active);
    }
    private void activateNewRechButton(boolean active) {
        bNouveau.setEnabled(active);
        bRechercher.setEnabled(active);
    }
    private void shouldActivateNewRech() {
        if (!((Pair)cbEtat.getSelectedItem()).key.equals("RIEN")) {
            activateNewRechButton(true);
        } else {
            activateNewRechButton(false);
        }
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     */
    private void initComponents() {
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        cbDoc = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        cbEtat = new javax.swing.JComboBox();
        bRechercher = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        bNouveau = new javax.swing.JButton();
        bChanger = new javax.swing.JButton();
        bSupprimer = new javax.swing.JButton();
        bExecuter = new javax.swing.JButton();
        bFermer = new javax.swing.JButton();
        
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Recherche"));
        jLabel2.setText("Document");
        
        Vector<Pair>cbDocItems = getDocsIds();
        cbDoc.setModel(new javax.swing.DefaultComboBoxModel(cbDocItems));
        cbDoc.setSelectedIndex(0);
        cbDoc.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        cbDoc.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JComboBox cb = (JComboBox)e.getSource();
                String petName = ((Pair)cb.getSelectedItem()).key;
                updateEtats(petName);
                //activateNewRechButton(false);
                shouldActivateNewRech();
                activateSupModButtons(false);
            }
        });
        
        jLabel3.setText("Etat");
        
        
        cbEtat.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        cbEtat.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                shouldActivateNewRech();
            }
        });
        
        bRechercher.setText("Rechercher");
        bRechercher.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bRechercherActionPerformed(evt);
            }
        });
        
        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jLabel2)
                .add(jLabel3))
                .add(39, 39, 39)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(cbDoc, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 356, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(jPanel1Layout.createSequentialGroup()
                .add(cbEtat, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 356, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 27, Short.MAX_VALUE)
                .add(bRechercher)))
                .addContainerGap())
                );
        jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                .add(jLabel2)
                .add(cbDoc, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 24, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                .add(cbEtat, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 24, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(jLabel3)
                .add(bRechercher))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                );
        
        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Configurations"));
        jScrollPane2.setViewportView(jTable1);
        
        jTable1.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount()==2) {
                    if (mode!=EXEC_FROM_CONF) {
                        bExecuterActionPerformed(null);
                    } else {
                        bChangerActionPerformed(null);
                    }
                }
            }
        });
        jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        jTable1.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                if(jTable1.getSelectedRow() >= 0) {
                    bSupprimer.setEnabled(true);
                    bChanger.setEnabled(true);
                    if(getMode()!=EXEC_FROM_CONF) bExecuter.setEnabled(true);
                } else {
                    bSupprimer.setEnabled(false);
                    bChanger.setEnabled(false);
                    bExecuter.setEnabled(false);
                }
            }
        });
        
        org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
                jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 557, Short.MAX_VALUE)
                .addContainerGap())
                );
        jPanel2Layout.setVerticalGroup(
                jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jPanel2Layout.createSequentialGroup()
                .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 327, Short.MAX_VALUE)
                .addContainerGap())
                );
        
        bNouveau.setText("Nouveau");
        bNouveau.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bNouveauActionPerformed(evt);
            }
        });
        
        bChanger.setText("Modifier");
        bChanger.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bChangerActionPerformed(evt);
            }
        });
        
        bSupprimer.setText("Supprimer");
        bSupprimer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bSupprimerActionPerformed(evt);
            }
        });
        bExecuter.setText("Exécuter");
        bExecuter.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bExecuterActionPerformed(evt);
            }
        });
        bFermer.setText("Fermer");
        bFermer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bFermerActionPerformed(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(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(layout.createSequentialGroup()
                .add(bExecuter)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(bSupprimer)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(bChanger)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(bNouveau)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 50, Short.MAX_VALUE)
                .add(bFermer)))
                .addContainerGap())
                );
        layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                .add(bNouveau)
                .add(bChanger)
                .add(bSupprimer)
                .add(bExecuter)
                .add(bFermer))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                );
        setTitle("Liste des configurations d'export");
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        pack();
        setLocationRelativeTo(getParent());

        // désactivation de certains boutons
        activateNewRechButton(false);
        activateSupModButtons(false);
        
        //Si on n'a qu'un seul document et qu'un seul état, on les sélectionne et on lance la recherche
        if (cbDocItems.size()==1) {
            String petName = ((Pair)cbDoc.getSelectedItem()).key;
            updateEtats(petName);
            
        }
        setGlassPane(interruptible = new InterruptibleInfiniteGlassPane());
        bExecuter.setEnabled(false);
    }
    
    private void bSupprimerActionPerformed(java.awt.event.ActionEvent evt) {
        if(JOptionPane.showConfirmDialog(this,"Etes vous sur de vouloir supprimer cette configuration ?","Suppression",JOptionPane.YES_NO_OPTION)==JOptionPane.NO_OPTION)
            return;
        try {
            DataLayerManager.getImplementation().deleteConfigExport(this.listeConfigs.get(jTable1.getSelectedRow()),user);
            bRechercherActionPerformed(null);
        } catch (Exception e) {
            logger.error("Erreur lors de la suppression d'une configuration",e);
        }
    }
    
    private void bFermerActionPerformed(java.awt.event.ActionEvent evt) {
        this.dispose();
    }
    private void bExecuterActionPerformed(java.awt.event.ActionEvent evt) {
        if (mode == EXEC_FROM_CONF) return;
        if (jTable1.getSelectedRow()<0) return;
        JFileChooser fc = new JFileChooser();
        fc.setFileFilter(new FileFilter(){
            @Override
            public boolean accept(File f) {
                return f.isDirectory() || f.getName().toUpperCase().endsWith(".XLS");
            }
            @Override
            public String getDescription() { return "Fichier Excel"; }
        });
        if(fc.showSaveDialog(this)==JFileChooser.APPROVE_OPTION) {
            _f = fc.getSelectedFile();
            // verification de la presence d'une extension
            // on cherche un '.' aux positions len-1, len-2, len-3, len-4
            String fileName = _f.getAbsolutePath();
            int len = fileName.length();
            if(fileName.substring(len-4).indexOf('.')<0) {
                fileName=fileName+".xls";
                _f = new File(fileName);
            }
            if(_f.exists()) {
                if(JOptionPane.showConfirmDialog(this,fileName+"\nCe fichier existe déjà. Voulez-vous l'écraser ?","Ecrasement",JOptionPane.YES_NO_OPTION)==JOptionPane.NO_OPTION)
                    return;
            }
            
            if (mode == EXEC_FROM_RECHERCHE) {
                try {
//                    ExportJob ej = new ExportJob();
//                    ej.setDataResultSet(ertm.getResultSet());
//                    ej.setDocumentId(dm.getId());
//                    ej.setEtatId(em.getParent().getId());
//                    ej.setElementId(em.getId());
//                    ej.setExportConfigId(Long.parseLong(listeConfigs.get(jTable1.getSelectedRow()).getId()));
//                    ej.setExportName("toto");
//                    ej.setFileName("toto");
//                    DataLayerManager.getImplementation().createExportJob(ej, user);
                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            String etatKey = ((Pair)cbEtat.getSelectedItem()).key;
                            Exporter ex = new Exporter(_f, ertm.getResultSet(), dm, etatKey, em, listeConfigs.get(jTable1.getSelectedRow()));
                            ex.setParentFrame(_sc);
                            interruptible.setThreadToInterrupt(ex);
                            getGlassPane().setVisible(true);
                            ex.execute();
                        }
                    });
                } catch (Exception e) {
                    logger.error(e);
                }
            } else {
                try {
                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            try {
                                String docKey  = ((Pair)cbDoc.getSelectedItem()).key;
                                String etatKey = ((Pair)cbEtat.getSelectedItem()).key;
                                em = (docModels.getDocumentById(docKey)).getEtatById(etatKey).getImportableElement();
                                
                                /**
                                 * CREATION de la requête en fonction de ce que l'on exporte
                                 */
                                
                                DataResultSet drs = DataLayerManager.getImplementation().getDataResultSetForExport(whatToExport, em, coll, budg, fic, SK1, SK2, user);
                                Exporter ex = new Exporter(_f, drs, dm, etatKey, em, listeConfigs.get(jTable1.getSelectedRow()));
                                ex.setParentFrame(_sc);
                                interruptible.setThreadToInterrupt(ex);
                                getGlassPane().setVisible(true);
                                ex.execute();
                            } catch(UnauthorizedException ex) {
                                JOptionPane.showMessageDialog(getParent(), ex.getMessage(), "Droits insuffisants", JOptionPane.WARNING_MESSAGE);
                            } catch (DataConfigurationException dae) {
                                logger.error("", dae);
                            } catch (SQLException sqle) {
                                logger.error("", sqle);
                            }
                        }
                    });
                } catch (Exception e) {
                    logger.error(e);
                }
            }
        }
    }
    
    public void showXLS() {
        try {
            getGlassPane().setVisible(false);
            setVisible(false);
            StartUrl.startUrl(_f.getAbsolutePath());
        } catch (Throwable t) {}
    }
    
    public void bRechercherActionPerformed(java.awt.event.ActionEvent evt) {
        jTable1.removeAll();
        try {
            String docKey = ((Pair)cbDoc.getSelectedItem()).key;
            String etatKey = ((Pair)cbEtat.getSelectedItem()).key;
            if (!"RIEN".equals(docKey) && !"RIEN".equals(etatKey)) {
                listeConfigs = DataLayerManager.getImplementation().getListeConfigsExport(docKey, etatKey, user);
                jTable1.setModel(new ConfigTableModel(listeConfigs));
            }
        } catch (Throwable t) {}
        
    }
    
    private void bChangerActionPerformed(java.awt.event.ActionEvent evt) {
        String docKey = ((Pair)cbDoc.getSelectedItem()).key;
        String etatKey = ((Pair)cbEtat.getSelectedItem()).key;
        DocumentModel dm2 = this.docModels.getDocumentById(docKey);
        EditConfig ec = new EditConfig(this, dm2, this.listeConfigs.get(jTable1.getSelectedRow()),user);
        ec.setVisible(true);
    }
    
    private void bNouveauActionPerformed(java.awt.event.ActionEvent evt) {
        String docKey = ((Pair)cbDoc.getSelectedItem()).key;
        String etatKey = ((Pair)cbEtat.getSelectedItem()).key;
        DocumentModel dm2 = this.docModels.getDocumentById(docKey);
        EditConfig ec = new EditConfig(this, dm2, etatKey,user);
        ec.setVisible(true);
    }
    
    private javax.swing.JButton bChanger;
    private javax.swing.JButton bNouveau;
    private javax.swing.JButton bRechercher;
    private javax.swing.JComboBox cbDoc;
    private javax.swing.JComboBox cbEtat;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JButton bSupprimer;
    private javax.swing.JButton bExecuter;
    private javax.swing.JButton bFermer;
    private Action escapeAction;
    
    // retourne la liste des id de documents
    private Vector<Pair> getDocsIds() {
        Vector<Pair> ret = new Vector<Pair>();
        if (docModels.getDocuments().size()>1)
            ret.add(new Pair("RIEN", "Sélectionnez un document"));
        for (DocumentModel dm2:docModels.getDocuments()) {
            // si le doc a au moins un etat exportable
            for (EtatModel em2:dm2.getEtats()) {
                if (em2.isExportable()) {
                    ret.add(new Pair(dm2.getId(),dm2.getTitre()));
                    break;
                }
            }
        }
        return ret;
    }
    // retourne la liste des id états d'un document
    private Vector<Pair> getEtatsIds(String docID) {
        Vector<Pair> ret = new Vector<Pair>();
        if (docModels.getDocumentById(docID).getEtats().size()>1)
            ret.add(new Pair("RIEN", "Sélectionnez un état"));
        for (EtatModel em2:docModels.getDocumentById(docID).getEtats()) {
            if (em2.isExportable())
                ret.add(new Pair(em2.getId(), em2.getTitre()));
        }
        return ret;
    }
    
    // mets à jour la liste des états
    private void updateEtats(String docID) {
        if (!"RIEN".equals(docID)) {
            Vector<Pair> cbEtatIds = getEtatsIds(docID);
            cbEtat.setModel(new DefaultComboBoxModel(cbEtatIds));
            if (cbEtatIds.size()==1) {
                cbEtat.setSelectedIndex(0);
                bRechercherActionPerformed(null);
                activateNewRechButton(true);
            }
        } else
            cbEtat.setModel(new DefaultComboBoxModel());
    }
    
    private class ConfigTableModel extends AbstractTableModel {
        private String[] columnNames = new String [] { "Code", "Libellé", "Créateur", "Date création" };
        private Vector<String[]> data = new Vector<String[]>();
        
        public ConfigTableModel(Vector<ConfigModel> d) {
            int row=0, column=0;
            for (ConfigModel cm:d) {
                column=0;
                String[] tmp = new String[4];
                tmp[column++] = cm.getCode();
                tmp[column++] = cm.getLibelle();
                tmp[column++] = cm.getOwner();
                tmp[column++] = cm.getDateCreation();
                data.add(tmp);
            }
        }
        
        @Override
        public String getColumnName(int column) {
            return columnNames[column];
        }
        
        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return false;
        }
        
        public int getColumnCount() {
            return columnNames.length;
        }
        
        public int getRowCount() {
            return (data!=null?data.size():0);
        }
        
        public Object getValueAt(int rowIndex, int columnIndex) {
            return (data!=null?data.get(rowIndex)[columnIndex]:"");
        }
    }
    @Override
    protected JRootPane createRootPane() {
        KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0);
        JRootPane rp = new JRootPane();
        escapeAction = new AbstractAction("Fermer") {
            /**
             * Comment for <code>serialVersionUID</code>
             */
            private static final long serialVersionUID = 1L;
            
            public void actionPerformed(ActionEvent evt) {
                setVisible(false);
            }
        };
        rp.registerKeyboardAction(escapeAction,"TOTOTOTO",ks,JComponent.WHEN_IN_FOCUSED_WINDOW);
        return rp;
    }
    
    public int getMode() {
        return mode;
    }
    
    public void setMode(int mode) {
        this.mode = mode;
    }
    
    public ConfigModel getConfigSelected() {
        return this.listeConfigs.get(jTable1.getSelectedRow());
    }
    
    public EtatResultTableModel getErtm() {
        return ertm;
    }
    
    public void setErtm(EtatResultTableModel ertm) {
        this.ertm = ertm;
    }
    
    public ElementModel getEm() {
        return em;
    }
    
    public void setEm(ElementModel em) {
        this.em = em;
    }
    
    public DocumentModel getDm() {
        return dm;
    }
    
    public void setDm(DocumentModel dm) {
        this.dm = dm;
    }
    
    /**
     * teste si le documentModel contient au moins un étatModel exportable
     */
    public static boolean docHasEtatToExport(DocumentsModel dms) {
        if (dms.getDocuments().size()<1) return false;
        
        for (DocumentModel dm:dms.getDocuments()) {
            for (EtatModel em:dm.getEtats()) {
                if (em.isExportable()) {
                    return true;
                }
            }
        }
        return false;
    }
    
    public Pair getBudg() {
        return budg;
    }
    
    public void setBudg(Pair budg) {
        this.budg = budg;
    }
    
    public Pair getColl() {
        return coll;
    }
    
    public void setColl(Pair coll) {
        this.coll = coll;
    }
    
    public void setWhatToExport(int whatToExport) {
        this.whatToExport = whatToExport;
    }
    
    public void setFic(String fic) {
        this.fic = fic;
    }
    
    public Pair getSK1() {
        return SK1;
    }
    
    public void setSK1(Pair sk1) {
        SK1 = sk1;
    }
    
    public Pair getSK2() {
        return SK2;
    }
    
    public void setSK2(Pair sk2) {
        SK2 = sk2;
    }
}
