/*******************************************************************************
 * This file is part of GECAMed.
 * 
 * GECAMed is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License (L-GPL) as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GECAMed 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 (L-GPL)
 * along with GECAMed.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * GECAMed is Copyrighted by the Centre de Recherche Public Henri Tudor (http://www.tudor.lu)
 * (c) CRP Henri Tudor, Luxembourg, 2008
 *******************************************************************************/
package lu.tudor.santec.gecamed.core.gui.widgets;

import java.awt.Color;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPasswordField;

import lu.tudor.santec.gecamed.core.gui.GECAMedIconNames;
import lu.tudor.santec.gecamed.core.gui.GECAMedModule;
import lu.tudor.santec.gecamed.core.gui.MainFrame;
import lu.tudor.santec.i18n.Translatrix;

import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.validation.Severity;
import com.jgoodies.validation.ValidationResult;
import com.jgoodies.validation.message.SimpleValidationMessage;
import com.jgoodies.validation.util.DefaultValidationResultModel;
import com.jgoodies.validation.view.ValidationResultViewFactory;


/**
 * a Dialog to enter the password after the system has been locked
 * 
 * @author Johannes Hermen johannes.hermen(at)tudor.lu
 *
 * @Version
 * <br>$Log: PasswordAskDialog.java,v $
 * <br>Revision 1.12  2008-09-25 09:43:06  heinemann
 * <br>fixed copyrights
 * <br>
 * <br>Revision 1.11  2008-07-07 12:07:57  heinemann
 * <br>complete - # 156: Add feedback to password dialog for superman mode
 * <br>http://santec.tudor.lu/trac/gecamed/ticket/156
 * <br>
 * <br>Revision 1.10  2008-01-15 09:29:38  hermen
 * <br>updated Javadoc and refactured code
 * <br>
 * <br>Revision 1.9  2008-01-07 13:02:50  hermen
 * <br>replaces mail.jar for base64 encoding for License reasons
 * <br>
 * <br>Revision 1.8  2007-12-06 14:46:44  hermen
 * <br>updated Javadoc and refactured code
 * <br>
 *
 */
public class PasswordAskDialog extends GECAMedBaseDialog implements ActionListener, KeyListener
{
    //~ Static fields/initializers =============================================

    private static final long serialVersionUID = 1L;
//    private JButton cancelButton;
//    private JButton okButton;
    private JLabel statusLabel;
    private JPasswordField pw1;
    private PanelBuilder builder;
    private String passHash;
    private boolean ok = false;
	private DefaultValidationResultModel validationResultModel;

    //~ Constructors ===========================================================
    /**
     * Creates a new PasswordChangeDialog.
     *
     * @param mainFrame a reference to the mainFrame of the Program to obtain all child-objects from
     * @param passHash the Password-Object, where the new pass is written to
     *
     * @throws HeadlessException
     */
    public PasswordAskDialog() {
//        super(parent);
//        this.setModal(true);
    	
    	super(Translatrix.getTranslationString("main.password"), true);
    	this.enableOkKeyMapping(true);
    	this.enableCancelKeyMapping(true);
    	/* ------------------------------------------------------- */
        // create components
    	/* ------------------------------------------------------- */
        this.setTitle(Translatrix.getTranslationString("main.password")); 
        this.pw1 = new JPasswordField();
        this.pw1.addActionListener(this);
//        this.cancelButton = new JButton(Translatrix.getTranslationString("core.cancel")); 
        this.cancelButton.addActionListener(this);
//        this.okButton = new JButton(Translatrix.getTranslationString("core.ok")); 
        this.okButton.addActionListener(this);
        this.statusLabel = new JLabel();
        this.statusLabel.setForeground(Color.RED);
        this.statusLabel.setHorizontalAlignment(JLabel.CENTER);
        /* ------------------------------------------------------- */
        // create Layout
        /* ------------------------------------------------------- */
//        FormLayout layout = new FormLayout( // cols
//        									"25dlu:grow, " +
//        									"2dlu," +
//        									"pref:grow," +
//        									"2dlu," +
//        									"75dlu:grow",
//        									// rows
//							                "20dlu," +
//							                "2dlu," +
//							                "pref," +
//							                "fill:15dlu," +
//							                "2dlu," +
//							                "pref," +
//							                "2dlu");
        
        FormLayout layout = new FormLayout( // cols
        									"2dlu," +
        									"fill:pref," +
        									"5dlu," +
        									"150dlu," +
        									"2dlu",
        									// rows
        									"3dlu," +
        									"15dlu," +  	// text
        									"3dlu," +
        									"15dlu," +  	// textfield
        									"fill:pref," + 	// spaciing for icon
        									"2dlu," +
        									"15dlu," +  	// validation 
        									"2dlu");
        
        builder = new PanelBuilder(layout);
        builder.getPanel().setOpaque(false);
//        builder.setBorder(new TitledBorder(Translatrix.getTranslationString("core.password"))); 
        CellConstraints cc = new CellConstraints();
        /* ------------------------------------------------------- */
        // add elements to Layout
        /* ------------------------------------------------------- */
        builder.add(new JLabel(GECAMedModule.getIcon(GECAMedIconNames.PASSWORD)), cc.xywh(2, 2, 1, 4));
        builder.add(new JLabel(Translatrix.getTranslationString("core.enterPassword")), cc.xy(4, 2));
        builder.add(this.pw1, cc.xy(4, 4));
//        builder.add(new JLabel(GECAMedModule.getIcon(GECAMedIconNames.PASSWORD)),       cc.xywh(1, 1, 1, 3));
//        builder.add(new JLabel(Translatrix.getTranslationString("core.enterPassword")), cc.xyw (3, 3, 1)); 
//        builder.add(this.pw1, 															cc.xyw (5, 3, 1));
//        builder.add(this.cancelButton, 													cc.xyw (1, 6, 3));
//        builder.add(this.okButton, 														cc.xyw (5, 6, 1));
        /* ================================================== */
		// create the validation things
		/* ================================================== */
		this.validationResultModel = new DefaultValidationResultModel();
		JComponent reportList = ValidationResultViewFactory
				.createReportList(validationResultModel);
		/* ------------------------------------------------------- */
//        builder.add(reportList, cc.xyw(1, 4, 5));
		builder.add(reportList, cc.xyw(2, 7, 3));
        /* ------------------------------------------------------- */
        this.pw1.addKeyListener(this);
		/* ------------------------------------------------------- */
        // show the Dialog
		/* ------------------------------------------------------- */
//        this.getContentPane().add(builder.getPanel());
        this.addMainPanel(builder.getPanel());
        this.pack();
        /* ================================================== */
    }

    //~ Methods ================================================================

    /* (non-Javadoc)
     * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
     */
    public void actionPerformed(ActionEvent e)
    {
        if (e.getSource().equals(this.cancelButton)) {
            // on cancel --> dispose
        	this.setVisible(false);
        } else if (e.getSource().equals(this.okButton) || e.getSource().equals(pw1)) {
            String pwStr1 = new String(pw1.getPassword());
             try {
				passHash = PasswordChangeDialog.getEncodedHash(pwStr1);
				if (passHash.equals(MainFrame.getCurrentUser().getPasswordhash())) {
					ok = true;
					this.setVisible(false);
				} else {
					/* ------------------------------------------------------- */
					ValidationResult validationResult = new ValidationResult();
					validationResult.add(new SimpleValidationMessage(
							Translatrix.getTranslationString("main.password.wrong"), Severity.ERROR));
					
					this.validationResultModel.setResult(ValidationResult.EMPTY);
					this.validationResultModel.setResult(validationResult);
					/* ------------------------------------------------------- */
				}
			} catch (Exception e1) {
				this.setVisible(false);
			}
             
        }
    }

    /**
     * just for testing.....
     *
     * @param args
     */
    public static void main(String[] args)
    {
        new PasswordAskDialog(); 
    }


    /**
     * shows the Dialog centered on the Screen.
     */
    public boolean showCentered() {
    	/* ================================================== */
    	this.ok = false;
    	MainFrame.showDialogCentered(this);
        return this.ok;
        /* ================================================== */
    }
    
    /**
	 * @return
	 */
	private ValidationResult doValidate(KeyEvent e) {
		/* ================================================== */
		ValidationResult validationResult = new ValidationResult();
		/* ------------------------------------------------------- */
		// if character uppercase and shift is not pressed,
		// caps lock must be on, hopefully
		/* ------------------------------------------------------- */
		if (Character.isUpperCase(e.getKeyChar())) {
			/* ------------------------------------------------------- */
			if (!e.isShiftDown())
				validationResult.add(new SimpleValidationMessage(
						Translatrix.getTranslationString("main.password.capslock"), Severity.WARNING));
			/* ------------------------------------------------------- */
		} 
		return validationResult;
		/* ================================================== */
	}
	
	
	private void fireKeyEvent(KeyEvent e) {
		/* ================================================== */
		this.validationResultModel.setResult(ValidationResult.EMPTY);
		this.validationResultModel.setResult(doValidate(e));
		this.pack();
		/* ================================================== */
	}

	public void keyPressed(KeyEvent e) {
		/* ====================================================== */
		fireKeyEvent(e);
		/* ====================================================== */
	}

	public void keyReleased(KeyEvent e) {
		/* ====================================================== */
		// TODO Auto-generated method stub
		/* ====================================================== */
	}

	public void keyTyped(KeyEvent e) {
		/* ====================================================== */
		// TODO Auto-generated method stub
		/* ====================================================== */
	}
}
