/*
 * Copyright
 *   2007 axYus - www.axyus.com
 *   2008 L.Meckert - laurent.meckert.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.plugin.signerfichier;

import java.util.Enumeration;
import java.awt.Component;
import java.util.Date;
import java.util.Vector;
import javax.swing.SwingUtilities;
import javax.swing.table.AbstractTableModel;
import org.netbeans.spi.wizard.Wizard;
import org.netbeans.spi.wizard.WizardPage;
import org.netbeans.spi.wizard.WizardPanelNavResult;

/**
 *
 * @author laurent.meckert
 */
public class CertListPanel extends WizardPage {
    private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(CertListPanel.class);
    private CertTableModel model;

    private class AliasListEntry {

        private String alias;
        private String issuedFor = null;
        private String details = null;
        private String bonhomme = null;
        private String emetteur = null;
        private Date dateDebut = null;
        private Date dateFin = null;

        AliasListEntry(Object oalias) {
            try {
                this.alias = (String) oalias;
                details = Actions.getInstance().getDetails(alias);
                issuedFor = Actions.getInstance().getIssuedFor(alias);
                bonhomme = Actions.getInstance().getNomBonhomme(alias);
                emetteur = Actions.getInstance().getEmetteur(alias);
                dateDebut = Actions.getInstance().getDateDebut(alias);
                dateFin = Actions.getInstance().getDateFin(alias);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public String toString() {
            return getIssuedFor() + "   (" + getAlias() + ")";
        }

        public String getAlias() {
            return alias;
        }

        public String getDetails() {
            return details;
        }

        /**
         * @return the issuedFor
         */
        public String getIssuedFor() {
            return issuedFor;
        }
        public String getBonhomme() { return bonhomme; }
        public String getEmetteur() { return emetteur; }
        public Date getDateDebut() { return dateDebut; }
        public Date getDateFin() { return dateFin; }
    }

    class CertTableModel extends AbstractTableModel {
        public Vector<AliasListEntry> data;

        public CertTableModel() {
            super();
            data = new Vector<AliasListEntry>();
        }

        @Override
        public String getColumnName(int column) {
            switch(column) {
                case 0: return "Délivré à";
                case 1: return "Délivré par";
                case 2: return "Valable de";
                default: return "à";
            }
        }

        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return false;
        }

        public Object getValueAt(int rowIndex, int columnIndex) {
            AliasListEntry alias = data.get(rowIndex);
            switch(columnIndex) {
                case 0: return alias.getBonhomme();
                case 1: return alias.getEmetteur();
                case 2: return alias.getDateDebut();
                default: return alias.getDateFin();
            }
        }

        @Override
        public Class<?> getColumnClass(int columnIndex) {
            switch(columnIndex) {
                case 0:
                case 1: return String.class;
                default: return Date.class;
            }
        }
        public void clear() {
            data = new Vector<AliasListEntry>();
            fireTableDataChanged();
        }
        public void addCert(AliasListEntry entry) {
            data.add(entry);
            fireTableRowsInserted(data.size(), data.size());
        }

        public int getRowCount() {
            return data.size();
        }

        public int getColumnCount() {
            return 4;
        }
        public AliasListEntry getAlias(int row) {
            return data.get(row);
        }

    }

    /** Creates new form CertListPanel */
    public CertListPanel() {

        String osname = System.getProperty("os.name");
        model = new CertTableModel();
        initComponents();


//        jListCertificates.setModel(new javax.swing.DefaultListModel());

        fillCertList();
        if (osname.startsWith("Windows")) {
            jPanelFromWindowsStore.setVisible(true);
            // nuisible tel quel mais a garder
            jRadioButtonWSelection.setVisible(false);
            jRadioButtonWTous.setVisible(false);
        } else {
            jButtonImportFromWindows.setVisible(false);
            jRadioButtonWSelection.setVisible(false);
            jRadioButtonWTous.setVisible(false);
        }
    //
    }

    public static final String getDescription() {
        return "Sélection de la clé privée";
    }

    @Override
    public WizardPanelNavResult allowNext(java.lang.String stepName, java.util.Map settings, Wizard wizard) {
        if (tblCerts.getSelectedRow()<0) {
            return WizardPanelNavResult.REMAIN_ON_PAGE;
        }
        boolean ret = Actions.getInstance().loadAlias(((AliasListEntry) model.getAlias(tblCerts.getSelectedRow())).getAlias());
        if (ret) {
            return WizardPanelNavResult.PROCEED;
        } else {
            return WizardPanelNavResult.REMAIN_ON_PAGE;
        }

    }

    protected void fillCertList() {
        try {
            Actions.getInstance().openCertFile();
        } catch (Exception e) {
            e.printStackTrace();
        }
//        ((javax.swing.DefaultListModel) jListCertificates.getModel()).clear();
        model.clear();

        try {
            if (Actions.getInstance().getAliases() == null) {
                return;
            }
            for (Enumeration e = Actions.getInstance().getAliases(); e.hasMoreElements();) {
                AliasListEntry le = new AliasListEntry(e.nextElement());
//                ((javax.swing.DefaultListModel) jListCertificates.getModel()).addElement(le);
                model.addCert(le);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected String validateContents(Component comp, Object o) {
        if (model.getRowCount() == 0) {
            return "Veuillez importer des clés SVP";
        }
        if (tblCerts.getSelectedRow()<0) {
            return "Sélectionner une clé SVP";
        } else {
            return null;
        }
    }

    /** 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.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        tblCerts = new javax.swing.JTable();
        jPanel2 = new javax.swing.JPanel();
        jPanelFromWindowsStore = new javax.swing.JPanel();
        jButtonImportFromWindows = new javax.swing.JButton();
        jRadioButtonWTous = new javax.swing.JRadioButton();
        jRadioButtonWSelection = new javax.swing.JRadioButton();
        jPanelFromFile = new javax.swing.JPanel();
        jButtonImportFromFile = new javax.swing.JButton();

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Sélectionner une clé..", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 10))); // NOI18N
        jPanel1.setMaximumSize(new java.awt.Dimension(294, 263));
        jPanel1.setOpaque(false);

        tblCerts.setModel(model);
        jScrollPane3.setViewportView(tblCerts);

        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(jScrollPane3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 505, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jScrollPane3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 120, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Importer des clés..", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 10))); // NOI18N

        jPanelFromWindowsStore.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jButtonImportFromWindows.setFont(new java.awt.Font("Tahoma", 0, 10));
        jButtonImportFromWindows.setText("<html>Depuis<br> le magasin de certificats de Windows...</html>");
        jButtonImportFromWindows.setToolTipText("<html>Vous permet de récupérer des clés privées en passant par les <br>libraries cryptographiques propres à Windows</html>");
        jButtonImportFromWindows.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonImportFromWindowsActionPerformed(evt);
            }
        });

        buttonGroup1.add(jRadioButtonWTous);
        jRadioButtonWTous.setFont(new java.awt.Font("Tahoma", 0, 10));
        jRadioButtonWTous.setText("Tout");
        jRadioButtonWTous.setToolTipText("<html>Importer tous vos certificats</html>");
        jRadioButtonWTous.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        jRadioButtonWTous.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);

        buttonGroup1.add(jRadioButtonWSelection);
        jRadioButtonWSelection.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        jRadioButtonWSelection.setSelected(true);
        jRadioButtonWSelection.setText("Choix");
        jRadioButtonWSelection.setToolTipText("<html>Sélectionner un certificat</html>");
        jRadioButtonWSelection.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        jRadioButtonWSelection.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jRadioButtonWSelection.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButtonWSelectionActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanelFromWindowsStoreLayout = new org.jdesktop.layout.GroupLayout(jPanelFromWindowsStore);
        jPanelFromWindowsStore.setLayout(jPanelFromWindowsStoreLayout);
        jPanelFromWindowsStoreLayout.setHorizontalGroup(
            jPanelFromWindowsStoreLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanelFromWindowsStoreLayout.createSequentialGroup()
                .addContainerGap()
                .add(jButtonImportFromWindows, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 109, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanelFromWindowsStoreLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jRadioButtonWSelection, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 66, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jRadioButtonWTous))
                .addContainerGap(134, Short.MAX_VALUE))
        );
        jPanelFromWindowsStoreLayout.setVerticalGroup(
            jPanelFromWindowsStoreLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanelFromWindowsStoreLayout.createSequentialGroup()
                .addContainerGap(13, Short.MAX_VALUE)
                .add(jPanelFromWindowsStoreLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(jButtonImportFromWindows, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 75, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jPanelFromWindowsStoreLayout.createSequentialGroup()
                        .add(jRadioButtonWSelection, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 31, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jRadioButtonWTous)))
                .addContainerGap())
        );

        jPanelFromFile.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jButtonImportFromFile.setFont(new java.awt.Font("Tahoma", 0, 10));
        jButtonImportFromFile.setText("<html>Depuis <br>  un fichier...</html>");
        jButtonImportFromFile.setToolTipText("<html>Ajouter des clés privées contenus dans un fichier<br>\nde type \"magasin de clés\"</html>");
        jButtonImportFromFile.setActionCommand("AddFromFile");
        jButtonImportFromFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonImportFromFileActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanelFromFileLayout = new org.jdesktop.layout.GroupLayout(jPanelFromFile);
        jPanelFromFile.setLayout(jPanelFromFileLayout);
        jPanelFromFileLayout.setHorizontalGroup(
            jPanelFromFileLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanelFromFileLayout.createSequentialGroup()
                .addContainerGap()
                .add(jButtonImportFromFile, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 109, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(43, Short.MAX_VALUE))
        );
        jPanelFromFileLayout.setVerticalGroup(
            jPanelFromFileLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanelFromFileLayout.createSequentialGroup()
                .addContainerGap()
                .add(jButtonImportFromFile, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 67, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(21, Short.MAX_VALUE))
        );

        org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanelFromFile, 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(jPanelFromWindowsStore, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jPanelFromWindowsStore, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jPanelFromFile, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(20, 20, 20)
                .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)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonImportFromFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonImportFromFileActionPerformed
        // TODO add your handling code here:
        try {
            Actions.getInstance().fillFromFile(null); // null pour forcer une selection de fichier

            fillCertList();//ici pas la peine

        } catch (Exception e) {
            e.printStackTrace();
        }
}//GEN-LAST:event_jButtonImportFromFileActionPerformed

    private void jButtonImportFromWindowsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonImportFromWindowsActionPerformed


        final Component me = (Component) this;
        //   Thread code = new Thread() {
        Runnable code = new Runnable() {
            //  @Override

            public void run() {
                try {
                    Actions.getInstance().fillFromWindows(SwingUtilities.getWindowAncestor(me), jRadioButtonWTous.isSelected());
                    fillCertList();

                //inutile  inclus dans fillcertList  validateContents(null, null);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        try {
            //   code.start();
            SwingUtilities.invokeLater(code);
        } catch (Throwable t) {
            t.printStackTrace();
        }








    }//GEN-LAST:event_jButtonImportFromWindowsActionPerformed

    private void jRadioButtonWSelectionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonWSelectionActionPerformed
        // TODO add your handling code here:
}//GEN-LAST:event_jRadioButtonWSelectionActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton jButtonImportFromFile;
    private javax.swing.JButton jButtonImportFromWindows;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanelFromFile;
    private javax.swing.JPanel jPanelFromWindowsStore;
    private javax.swing.JRadioButton jRadioButtonWSelection;
    private javax.swing.JRadioButton jRadioButtonWTous;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTable tblCerts;
    // End of variables declaration//GEN-END:variables
}
