/*
 * Copyright
 *   2007 axYus - www.axyus.com
 *   2007 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.dropUsers;

import fr.gouv.finances.dgfip.xemelios.common.Crypter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 *
 * @author chm
 */
public class DlgResetAdminPassword extends javax.swing.JDialog {
    private Connection con = null;
    private String[] users=null;
    private String login = null;

    /** Creates new form DlgResetAdminPassword */
    public DlgResetAdminPassword(Connection con) {
        super((JFrame)null, "Modification du mot de passe administrateur",true);
        this.con=con;
        loadUsers();
        initComponents();
    }

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

        jLabel1 = new javax.swing.JLabel();
        scroller = new javax.swing.JScrollPane();
        lstUsers = new javax.swing.JList(users);
        jSeparator1 = new javax.swing.JSeparator();
        lblMessage = new javax.swing.JLabel();
        lblPwd1 = new javax.swing.JLabel();
        pwd1 = new javax.swing.JPasswordField();
        lblPwd2 = new javax.swing.JLabel();
        pwd2 = new javax.swing.JPasswordField();
        pbSave = new javax.swing.JButton();
        pbClose = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("Utilisateurs connus");

        lstUsers.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        lstUsers.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                lstUsersValueChanged(evt);
            }
        });
        scroller.setViewportView(lstUsers);

        lblMessage.setText("Sélectionnez l'administrateur dans la liste");

        lblPwd1.setLabelFor(pwd1);
        lblPwd1.setText("Nouveau mot de passe");
        lblPwd1.setEnabled(false);

        pwd1.setEnabled(false);
        pwd1.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                pwd1CaretUpdate(evt);
            }
        });

        lblPwd2.setLabelFor(pwd2);
        lblPwd2.setText("Confirmez");
        lblPwd2.setEnabled(false);

        pwd2.setEnabled(false);
        pwd2.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                pwd2CaretUpdate(evt);
            }
        });

        pbSave.setText("Enregistrer");
        pbSave.setEnabled(false);
        pbSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pbSaveActionPerformed(evt);
            }
        });

        pbClose.setText("Fermer");
        pbClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pbCloseActionPerformed(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(layout.createSequentialGroup()
                        .add(scroller, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 145, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(pbSave)
                            .add(lblPwd2)
                            .add(lblPwd1)
                            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                                .add(org.jdesktop.layout.GroupLayout.LEADING, pwd1)
                                .add(org.jdesktop.layout.GroupLayout.LEADING, pwd2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 122, Short.MAX_VALUE)))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .add(pbClose, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 77, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(jLabel1))
                .addContainerGap())
            .add(jSeparator1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 412, Short.MAX_VALUE)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(lblMessage, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 388, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jLabel1)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(scroller, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 212, Short.MAX_VALUE)
                    .add(layout.createSequentialGroup()
                        .add(lblPwd1)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(pwd1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(23, 23, 23)
                        .add(lblPwd2)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(pwd2, 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(pbSave)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 53, Short.MAX_VALUE)
                        .add(pbClose)))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jSeparator1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 10, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(lblMessage)
                .add(18, 18, 18))
        );

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

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

    private void pbSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbSaveActionPerformed
        char[] p1 = pwd1.getPassword();
        char[] p2 = pwd2.getPassword();
        if(!new String(p1).equals(new String(p2))) {
            JOptionPane.showMessageDialog(this, "Les mots de passe sont différents", "Erreur", JOptionPane.ERROR_MESSAGE);
            return;
        }
        String cryptedPwd = Crypter.cryptPassword(new String(p1));
        PreparedStatement ps = null;
        try {
            ps = con.prepareStatement("UPDATE DGCP_USERS SET PASSWORD=? WHERE LOGIN=?");
            ps.setString(1,cryptedPwd);
            ps.setString(2, login);
            ps.executeUpdate();
            lblMessage.setText("Mot de passe correctement modifié");
        } catch(SQLException sqlEx) {
            sqlEx.printStackTrace();
        } finally {
            try { ps.close() ; } catch(Throwable t) {}
        }
    }//GEN-LAST:event_pbSaveActionPerformed

    private void lstUsersValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_lstUsersValueChanged
        if(lstUsers.getSelectedIndex()>=0) {
            login = (String)lstUsers.getSelectedValue();
            pwd1.setText("");
            pwd1.setEnabled(true);
            pwd2.setText("");
            pwd2.setEnabled(true);
            lblPwd1.setEnabled(true);
            lblPwd2.setEnabled(true);
            lblMessage.setText("Saisissez le nouveau mot de passe et confirmez-le");
        } else {
            pwd1.setEnabled(false);
            pwd2.setEnabled(false);
            lblPwd1.setEnabled(false);
            lblPwd2.setEnabled(false);
            lblMessage.setText("Sélectionnez l'administrateur dans la liste");
        }
    }//GEN-LAST:event_lstUsersValueChanged

    private void pwd1CaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_pwd1CaretUpdate
        updateSaveButton();
    }//GEN-LAST:event_pwd1CaretUpdate

    private void pwd2CaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_pwd2CaretUpdate
        updateSaveButton();
    }//GEN-LAST:event_pwd2CaretUpdate

    /**
    * @param args the command line arguments
    */

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JLabel lblMessage;
    private javax.swing.JLabel lblPwd1;
    private javax.swing.JLabel lblPwd2;
    private javax.swing.JList lstUsers;
    private javax.swing.JButton pbClose;
    private javax.swing.JButton pbSave;
    private javax.swing.JPasswordField pwd1;
    private javax.swing.JPasswordField pwd2;
    private javax.swing.JScrollPane scroller;
    // End of variables declaration//GEN-END:variables

    private void loadUsers() {
        Statement st = null;
        ResultSet rs = null;
        Vector<String> v = new Vector<String>();
        try {
            st = con.createStatement();
            rs = st.executeQuery("SELECT LOGIN FROM DGCP_USERS ORDER BY 1");
            while(rs.next()) {
                v.add(rs.getString(1));
            }
            rs.close();
            rs=null;
        } catch(SQLException sqlEx) {
            sqlEx.printStackTrace();
        } finally {
            if(rs!=null) {
                try { rs.close(); } catch(Throwable t) {}
            }
            if(st!=null) {
                try { st.close() ; } catch(Throwable t) {}
            }
        }
        users = new String[v.size()];
        v.toArray(users);
    }

    private void updateSaveButton() {
        boolean ret = pwd1.getPassword().length>0 && pwd2.getPassword().length>0;
        pbSave.setEnabled(ret);
    }
}
