/*
 * Copyright 
 *   2005 axYus - www.axyus.com
 *   2005 C.Marchand - christophe.marchand@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 General Public License as published by
 * the Free Software Foundation; either version 2 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 General Public License for more details.
 * 
 * You should have received a copy of the GNU 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.auth.dgcp;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.Arrays;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;

import org.apache.log4j.Logger;

import fr.gouv.finances.cp.utils.ui.DisplayExceptionDlg;
import fr.gouv.finances.cp.xemelios.ui.MainWindow;
import fr.gouv.finances.dgfip.xemelios.auth.AuthEngine;
import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;

/**
 *
 * @author  chm
 */
public class DlgChangePassword extends javax.swing.JDialog {
    private static final Logger logger = Logger.getLogger(DlgChangePassword.class);
    private Action escapeAction;
    private boolean ret;

    
    /** Creates new form DlgChangePassword */
    public DlgChangePassword(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        getRootPane().setDefaultButton(pbOk);
        setLocationRelativeTo(getParent());
    }
    
    /** 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() {
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        dfOldPasswd = new javax.swing.JPasswordField();
        dfNewPasswd = new javax.swing.JPasswordField();
        dfConfirmPasswd = new javax.swing.JPasswordField();
        pbOk = new javax.swing.JButton();
        pbCancel = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Changement de mot de passe");
        jLabel1.setText("Ancien mot de passe");

        jLabel2.setText("Nouveau mot de passe");

        jLabel3.setText("Confirmer le nouveau mot de passe");

        pbOk.setText("Ok");
        pbOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pbOkActionPerformed(evt);
            }
        });

        pbCancel.setAction(escapeAction);
        pbCancel.setText("Annuler");

        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(jLabel3)
                    .add(jLabel2)
                    .add(jLabel1))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(dfNewPasswd, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 125, Short.MAX_VALUE)
                    .add(dfConfirmPasswd, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 125, Short.MAX_VALUE)
                    .add(dfOldPasswd, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 125, Short.MAX_VALUE))
                .addContainerGap())
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap(114, Short.MAX_VALUE)
                .add(pbOk)
                .add(19, 19, 19)
                .add(pbCancel)
                .add(116, 116, 116))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel1)
                    .add(dfOldPasswd, 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(jLabel2)
                    .add(dfNewPasswd, 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(jLabel3)
                    .add(dfConfirmPasswd, 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(pbOk)
                    .add(pbCancel))
                .addContainerGap())
        );
        pack();
    }// </editor-fold>//GEN-END:initComponents

    private DgcpAuthEngine getAuthEngine() {
        return (DgcpAuthEngine)AuthEngine.Holder.getAuthEngine();
    }

    private void pbOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbOkActionPerformed
        char[] oldPwd = dfOldPasswd.getPassword();
        char[] newPwd = dfNewPasswd.getPassword();
        char[] confirm = dfConfirmPasswd.getPassword();
        if(!Arrays.equals(newPwd,confirm)) {
            JOptionPane.showMessageDialog(this,"Les nouveaux mots de passe ne sont pas identiques entre eux.","Erreur",JOptionPane.ERROR_MESSAGE);
            dfNewPasswd.setText("");
            dfConfirmPasswd.setText("");
            dfNewPasswd.grabFocus();
            return;
        }
        if(newPwd.length==0) {
            JOptionPane.showMessageDialog(this,"Le nouveau mot de passe ne peut être vide.","Erreur",JOptionPane.ERROR_MESSAGE);
            dfNewPasswd.grabFocus();
            return;
        }
        XemeliosUser user = MainWindow.instance.getConnectedUser();
        try {
            if (getAuthEngine().createUser(user.getId(), new String(oldPwd)) == null) {
                JOptionPane.showMessageDialog(this,"L'ancien mot de passe est incorrect.","Erreur",JOptionPane.ERROR_MESSAGE);
                dfOldPasswd.setText("");
                dfOldPasswd.grabFocus();
                return;
            }
        } catch(Exception ex) {
                JOptionPane.showMessageDialog(this,"Impossible de modifier le mot de passe pour l'instant.","Erreur",JOptionPane.ERROR_MESSAGE);
                logger.debug("while validating old password",ex);
                return;
        }
        // bon, maintenant, on change le mot de passe
        try {
            if(getAuthEngine().modifyPassword(user.getId(), new String(newPwd))) {
                JOptionPane.showMessageDialog(this,"Mot de passe correctement modifié.","",JOptionPane.INFORMATION_MESSAGE);
                setVisible(false);
            }
        } catch(Throwable t) {
            DisplayExceptionDlg dispDlg = new DisplayExceptionDlg(this,t);
        }
    }//GEN-LAST:event_pbOkActionPerformed
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPasswordField dfConfirmPasswd;
    private javax.swing.JPasswordField dfNewPasswd;
    private javax.swing.JPasswordField dfOldPasswd;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JButton pbCancel;
    private javax.swing.JButton pbOk;
    // End of variables declaration//GEN-END:variables

    protected JRootPane createRootPane() {
	    KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0);
	    JRootPane rp = new JRootPane();
		escapeAction = new AbstractAction("Annuler") {
		    /**
             * Comment for <code>serialVersionUID</code>
             */
            private static final long serialVersionUID = 1L;

            public void actionPerformed(ActionEvent evt) {
                ret = false;
		        setVisible(false);
		    }
		};
	    rp.registerKeyboardAction(escapeAction,"TOTOTOTO",ks,JComponent.WHEN_IN_FOCUSED_WINDOW);
	    return rp;
	}
    
}
