/*
 * 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;


/*
 * DlgKeystore.java
 *
 * Created on 23 septembre 2008, 13:07
 */
import javax.swing.JOptionPane;

/**
 *
 * @author  laurent.meckert
 */
public class DlgKeystore extends javax.swing.JDialog {

   int mode; // ouverture du keystore ou d'une cle
   public static final int MODE_KEYSTORE = 1;
   public static final int MODE_ALIAS = 2;
   protected IKeystoreValider valider;
   int nbAttempts = 0;

   /** Creates new form DlgKeystore
    * @param parent
    * @param modal 
    */
   public DlgKeystore(java.awt.Frame parent, boolean modal) {
      super(parent, modal);
      initComponents();
      setLocationRelativeTo(parent);
      getRootPane().setDefaultButton(jButtonValider);
   }

   public void setMode(int amode) throws Exception {
      if (amode != MODE_KEYSTORE && amode != MODE_ALIAS) {
         throw new Exception("Mode Incorrect");
      }
      mode = amode;
   }

   /** 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() {

      jPasswordField1 = new javax.swing.JPasswordField();
      jLabel1 = new javax.swing.JLabel();
      jButtonValider = new javax.swing.JButton();

      setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

      jLabel1.setText("Mot de passe :");

      jButtonValider.setText("Valider");
      jButtonValider.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
               jButtonValiderActionPerformed(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.LEADING)
                                          .add(jLabel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 105, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                          .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                                               .add(jPasswordField1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 302, Short.MAX_VALUE)
                                               .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                               .add(jButtonValider)))
                                     .addContainerGap())
                                );
      layout.setVerticalGroup(
                              layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                              .add(layout.createSequentialGroup()
                                   .add(27, 27, 27)
                                   .add(jLabel1)
                                   .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                   .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                                        .add(jButtonValider)
                                        .add(jPasswordField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                                   .addContainerGap(30, Short.MAX_VALUE))
                              );

      pack();
   }// </editor-fold>//GEN-END:initComponents

   private void validerKeystore() {
      ++nbAttempts;
      getValider().setKeystorePassword(jPasswordField1.getText());
      // maintenant on connait le mot de passe
      // on peut charger le fichier et presenter 
      //la liste des alias
      try {
         valider.loadKeystore();
      } catch (Exception e) {
         e.printStackTrace();
      }
      if (valider.loadKsOK() || nbAttempts > 2) {
         nbAttempts = 0;// pour la prochaine fois
         hide();
      } else {

         JOptionPane.showMessageDialog(null,
                 "Echec du chargement. Peut être une erreur de mot de passe ?",
                 "Echec du chargement",
                 JOptionPane.ERROR_MESSAGE);

      }
   }

   private void validerAlias() {
      ++nbAttempts;
      getValider().setAliasPassword(jPasswordField1.getText());
      // maintenant on connait le mot de passe
      // on peut charger le fichier et presenter 
      //la liste des alias
      try {
         valider.loadAlias();
      } catch (Exception e) {
         e.printStackTrace();
      }
      if (valider.loadPkOK() || (!valider.algoIdOK()) || nbAttempts > 2) {

         nbAttempts = 0;// pour la prochaine fois
         setVisible(false);
      } else {
         JOptionPane.showMessageDialog(null,
                 "Echec du chargement. Peut être une erreur de mot de passe ?",
                 "Echec du chargement",
                 JOptionPane.ERROR_MESSAGE);
      }

   }

   private void jButtonValiderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonValiderActionPerformed
      // TODO add your handling code here:
      if (mode == MODE_KEYSTORE) {
         validerKeystore();
      } else if (mode == MODE_ALIAS) {
         validerAlias();
      }

   }//GEN-LAST:event_jButtonValiderActionPerformed

   /**
    * @param args the command line arguments
    */
   public static void main(String args[]) {
      java.awt.EventQueue.invokeLater(new Runnable() {

         public void run() {
            DlgKeystore dialog = new DlgKeystore(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 jButtonValider;
   private javax.swing.JLabel jLabel1;
   private javax.swing.JPasswordField jPasswordField1;
   // End of variables declaration//GEN-END:variables

   public IKeystoreValider getValider() {
      return valider;
   }

   public void setValider(IKeystoreValider valider) {
      this.valider = valider;
   }
}
