/*
 * 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.FlowLayout;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.Arrays;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JRootPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.KeyStroke;

import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;

import fr.gouv.finances.cp.utils.ui.IhmFactory;

/**
 * Cette boite de dialogue demande à l'utilisateur un nouveau login/mot de passe
 * pour creer un nouvel utilisateur
 * @author chm
 */
public class NewAdmin extends JDialog {
	static {
		System.out.println(System.getProperty("os.name"));
		if(System.getProperty("os.name").toLowerCase().indexOf("win")>=0)
			setDefaultLookAndFeelDecorated(true);
	}
	/**
	 * Comment for <code>serialVersionUID</code>
	 */
	private static final long serialVersionUID = 3616731564957317170L;
	public static final String TITLE = "Création de mot de passe";
	private JTextField dfLogin;
	private JPasswordField pwd1, pwd2;
	private JButton pbOk, pbCancel;
	private boolean ret;
//	private String[] newPassword;
	private Action escapeAction;
	
	/**
	 * @param owner
	 * @throws java.awt.HeadlessException
	 */
	public NewAdmin(JFrame owner) throws HeadlessException {
		super(owner,TITLE,true);
		initialize();
	}
	
	protected void initialize() {
		int sepInfo = 2;
		int lineInfo = sepInfo + 2;

		int sepRWline = lineInfo + 2;
		int loginLine = sepRWline + 2;
		int pwdLine = loginLine + 2;
		int confirmLine = pwdLine + 2;
		
//		int sepROline = confirmLine + 2;
//		int pwdLine2 = sepROline + 2;
//		int confirmLine2 = pwdLine2 + 2;

		int buttonLine = confirmLine + 2;

		JTextArea area = null;
		
		FormLayout fl = new FormLayout(
				//        0     1     2    3    4    5
/*						"1dlu,20dlu,pref,1dlu,pref,1dlu", */
						"3dlu,20dlu,pref,3dlu,pref,3dlu",
				"7dlu,"+                                   // 0
				"pref,"+                                   // 1  --sepInfo
				"3dlu,"+                                   // 2	
				"pref,"+                                   // 3  --lineInfo
				"7dlu,"+                                   // 4
				"pref,"+                                   // 5  --sepRWline
				"3dlu,"+                                   // 6 
				"pref,"+									//	 --loginLine
				"3dlu,"+
				"pref,"+                                   // 7  --pwdLine
				"1dlu,"+                                   // 8
				"pref,"+                                   // 9  --confirmLine
				"10dlu,"+                                  // 10
				"pref,"+                                   // 11 --buttonLine
				"10dlu");                                   // 18
		CellConstraints cc = new CellConstraints();
		PanelBuilder pb = new PanelBuilder(fl);
		IhmFactory iF=IhmFactory.newInstance();

		pb.addSeparator("Informations",					cc.xyw(2,sepInfo,4));
		pb.add(area = new JTextArea(), 					cc.xyw(3,lineInfo,3));
		
		pb.addSeparator("Administrateur",	cc.xyw(2,sepRWline,4));
		pb.add(iF.newLabel("Identifiant","normal"),		cc.xy (3,loginLine));
		pb.add(dfLogin = new JTextField(),				cc.xy (5,loginLine));
		pb.add(iF.newLabel("Mot de passe","normal"),	cc.xy (3,pwdLine));
		pb.add(pwd1 = new JPasswordField(),				cc.xy (5,pwdLine));
		pb.add(iF.newLabel("Confirmer","normal"),		cc.xy (3,confirmLine));
		pb.add(pwd2 = new JPasswordField(),				cc.xy (5,confirmLine));

		JPanel bPane = new JPanel(new FlowLayout(FlowLayout.CENTER));
		pbCancel = new JButton(escapeAction);
		pbOk = new JButton("Ok");
		bPane.add(pbOk); bPane.add(pbCancel); 
		
		pb.add(bPane,									cc.xyw(2,buttonLine,4));
		
		pwd1.setColumns(15);
		add(pb.getPanel());
		
		area.setEditable(false);
		area.setLineWrap(true);
		area.setRows(3);
		area.setBackground(getBackground());
		area.setText("Afin de protéger l'accès à cet outil,\nvous devez créer un super-utilisateur dont le rôle sera d'administrer les utilisateurs.");
		
		pbOk.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				checkResponse();
			}
		});
		getRootPane().setDefaultButton(pbOk);
		pack();
		setLocationRelativeTo(getParent());
	}
	@Override
	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;
	}
	protected void checkResponse() {
		ret = true;
		if(pwd1.getPassword()==null || pwd1.getPassword().length==0) {
			JOptionPane.showMessageDialog(this,"Les champs de mot de passe sont obligatoires","Erreur de saisie",JOptionPane.WARNING_MESSAGE);
			pwd1.grabFocus();
			ret = false;
		}
		if(ret &&(pwd2.getPassword()==null || pwd2.getPassword().length==0)) {
			JOptionPane.showMessageDialog(this,"Les champs de mot de passe sont obligatoires","Erreur de saisie",JOptionPane.WARNING_MESSAGE);
			pwd2.grabFocus();
			ret = false;
		}
		if(ret && !Arrays.equals(pwd1.getPassword(),pwd2.getPassword())) {
			JOptionPane.showMessageDialog(this,"Vous devez saisir le même mot de passe dans les deux champs","Erreur de saisie",JOptionPane.WARNING_MESSAGE);
			ret = false;
		}
		if(ret) {
			setVisible(false);
		}
	}
	public boolean run() {
		setVisible(true);
		toFront();
		return ret;
	}
	public String getNewPassword() { return new String(pwd1.getPassword()); }
	public String getNewLogin() { return dfLogin.getText(); }
	@Override
	public void setVisible(boolean b) {
		dfLogin.grabFocus();
		super.setVisible(b);
	}
}
