/*
 * Copyright
 *   2007 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 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.auth;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

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;
import fr.gouv.finances.cp.xemelios.common.Constants;

/**
 * Permet de demander le mot de passe à l'utilisateur
 * @author chm
 */
public class DlgLogin extends JDialog {
	/**
	 * Comment for <code>serialVersionUID</code>
	 */
	private static final long serialVersionUID = 3546362837975971889L;
	static {
		System.out.println(System.getProperty("os.name"));
		if(System.getProperty("os.name").toLowerCase().indexOf("win")>=0)
			setDefaultLookAndFeelDecorated(true);
	}
	public static final transient String DLG_TITLE="Authentification...";
	private JTextField txt1;
	private JPasswordField pwd1;
	private JButton pbOk, pbCancel;
	private boolean ret;
	
	private String userName;
	private String password;
	private Action escapeAction;
	
	private Properties props;

	
	public DlgLogin(JFrame owner) {
		super(owner,DLG_TITLE,true);
		File f = new File(System.getProperty("user.home"),"xemelios.properties");
		props = new Properties();
		if(f.exists()) {
			try {
				props.load(new FileInputStream(f));
			} catch(IOException ioEx) {}
		}
		initComposants();
	}
	
	protected void initComposants() {
		int sepInfo = 2;
		int lineInfo = sepInfo + 2;
		int sepData = lineInfo + 2;
		int userLine = sepData + 2;
		int pwdLine = userLine + 2;
		int buttonLine = pwdLine + 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
				"3dlu,"+                                   // 2
				"pref,"+                                   // 3
				"7dlu,"+                                   // 4
				"pref,"+                                   // 5
				"3dlu,"+                                   // 6
				"pref,"+                                   // 7
				"3dlu,"+                                   // 8
				"pref,"+                                   // 9
				"10dlu,"+                                  // 10
				"pref,"+                                   // 11
				"3dlu");                                   // 12
		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("Données",						cc.xyw(2,sepData,4));
		pb.add(iF.newLabel("Utilisateur","normal"),	cc.xy (3,userLine));
		pb.add(txt1 = new JTextField(),				cc.xy (5,userLine));
		pb.add(iF.newLabel("Mot de passe","normal"),	cc.xy (3,pwdLine));
		pb.add(pwd1 = new JPasswordField(),				cc.xy (5,pwdLine));

		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());
//		add(pbCancel); add(pbOk);
		
		area.setEditable(false);
		area.setLineWrap(true);
		area.setRows(3);
		area.setBackground(getBackground());
//		area.setColumns(70);
		area.setText("Veuillez saisir le mot de passe\r\npour accéder à "+Constants.NOM_APP);
		
		pbOk.setDefaultCapable(true);
		pbOk.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(txt1.getText()==null || txt1.getText().length()==0) {
					JOptionPane.showMessageDialog(DlgLogin.this,"L'identifiant est obligatoire","Erreur",JOptionPane.ERROR_MESSAGE);
					txt1.grabFocus();
					return;
				}
				if(pwd1.getPassword().length==0) {
					JOptionPane.showMessageDialog(DlgLogin.this,"Le mot de passe est obligatoire","Erreur",JOptionPane.ERROR_MESSAGE);
					pwd1.grabFocus();
					return;
				}
				userName = txt1.getText();
				password = new String(pwd1.getPassword());
				ret = true;
				props.setProperty("last.login",userName);
				setVisible(false);
				try {
					props.store(new FileOutputStream(new File(System.getProperty("user.home"),"xemelios.properties")),"");
				} catch(IOException ioEx) {}
			}
		});
		getRootPane().setDefaultButton(pbOk);
		pack();
		setLocationRelativeTo(getParent());
	}
	public boolean run() {
		String lastLogin = props.getProperty("last.login"); 
		txt1.setText(lastLogin);
		pwd1.setText("");
		if(lastLogin!=null && lastLogin.length()>0) pwd1.grabFocus();
		else txt1.grabFocus();
		setVisible(true);
		return ret;
	}
	
	public String getPassword() { return password; }
	public String getUserName() { return userName; }
	@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;
	}
	/* (non-Javadoc)
	 * @see java.awt.Component#setVisible(boolean)
	 */
	@Override
	public void setVisible(boolean b) {
		//txt1.grabFocus();
		super.setVisible(b);
	}
}
