/*
 * $Id: ChangeUserPasswordForm.java,v 1.9 2004/11/10 15:02:48 koppy Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 *
 * $Log: ChangeUserPasswordForm.java,v $
 * Revision 1.9  2004/11/10 15:02:48  koppy
 * Projektweite Überarbeitung von Error-Logs, Stacktraces,..
 *
 * Revision 1.8  2004/08/30 20:06:35  marbobo
 * + Verbesserung des Redirectmechanismus
 *
 * Revision 1.7  2004/08/08 15:16:00  marbobo
 * + Refactorings und Behandlung von Fehlermeldungen
 *
 * Revision 1.6  2004/08/02 20:19:17  marbobo
 * + Refactorings und Behandlung von Fehlermeldungen
 *
 * Revision 1.5  2004/07/09 14:29:14  marbobo
 * + Namen des Benutzers anzeigen für welches das Passwort geändert wird
 *
 * Revision 1.4  2004/03/18 01:20:31  marbobo
 * EditUserAction und EditUserForm auf request-scope umgestellt
 *
 * Revision 1.3  2003/12/24 10:12:06  bigmac
 * Projektweite Import-Optimierung
 *
 * Revision 1.2  2003/10/06 09:57:01  marbobo
 * +Zufälligespasswort generieren
 * +EMail verschicken
 *
 * Revision 1.1  2003/08/22 16:35:23  marbobo
 * Initiale Version
 *
 */

package vkc.administration.form;


import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;

import vkc.db.entities.VKCUser;
import vkc.db.serializer.VKCUserSerializer;
import vkc.exception.DBException;
import vkc.misc.VKCLogManager;
import vkc.util.StringUtils;
import vkc.util.VKCCoder;
import vkc.view.bean.UserInfo;
import vkc.view.form.BasicActionForm;

/**
 * Form bean zum Ändern des Benutzerpassworts
 *
 * @author marbobo
 */

public final class ChangeUserPasswordForm extends BasicActionForm {
	private boolean passwordChanged = false;

	private Integer userId = null;

	private String adminpassword = "";
	private String newpassword = "";
	private String repassword = "";
	private String redirect	= "";

	/**
	 * Reset der Eingabefelder auf Defaultwerte
	 *
	 * @param mapping The mapping used to select this instance
	 * @param request The servlet request we are processing
	 */
	public void reset( ActionMapping mapping, HttpServletRequest request ) {
		super.reset( mapping, request );

		passwordChanged = false;

		userId = null;

		adminpassword = "";
		newpassword = "";
		repassword = "";
		redirect = "";
	}

	/**
	 * Validierung der Eingabefelder
	 *
	 * @param mapping The mapping used to select this instance
	 * @param request The servlet request we are processing
	 */
	public ActionErrors validate( ActionMapping mapping, HttpServletRequest request ) {
		ActionErrors errors = new ActionErrors();
        
		//Passwort ändern
		if ( request.getParameter( "action.change.password" ) != null || request.getParameter( "action.random.password" ) != null ) {
			if ( isEmpty( getAdminpassword() ) ) {
				errors.add( "oldpassword.mismatch", new ActionError( "error.adminpassword.mismatch" ) );
			}
    
			if ( request.getParameter( "action.change.password" ) != null ) {
				if ( getNewpassword().length() < 6 || getRepassword().length() < 6 ) {
					errors.add( "shortpassword", new ActionError( "vkc.administration.error.password.tooshort" ) );
				}

				if ( !getNewpassword().equals( getRepassword() ) ) {
					errors.add( "mismatchpassword", new ActionError( "vkc.administration.error.password.mismatch" ) );
				}
			}

			VKCUser user = getUser();
			String currentPassword = user.getPassword();

			if ( !isEmpty( currentPassword ) && !isEmpty( getAdminpassword() ) ) {
				String userName = user.getUser();
				byte[] md5Bytes = null;
				
				try {
					md5Bytes = ( userName + getAdminpassword() ).getBytes( "ISO-8859-1" );
				} catch ( UnsupportedEncodingException e ) {
					VKCLogManager.errorLog(this, "", e.getMessage(),e);
				}
	
				MessageDigest digest = null;
				
				try {
					digest = MessageDigest.getInstance( "MD5" );
				} catch ( NoSuchAlgorithmException e1 ) {
					VKCLogManager.errorLog(this, "", e1.getMessage(),e1);
				}
				
				digest.reset();
				digest.update( md5Bytes );
				byte[] fingerPrint = digest.digest();
				fingerPrint = VKCCoder.base64Encode( fingerPrint );
				String md5Password = null;
				
				try {
					md5Password = new String( fingerPrint, "ISO-8859-1" );
				} catch ( UnsupportedEncodingException e2 ) {
					VKCLogManager.errorLog(this, "", e2.getMessage(),e2);
				}
				
				//Passwort stimmt nicht überein
				if ( !currentPassword.trim().equals( md5Password ) ) {
					errors.add( "oldpassword.mismatch", new ActionError( "error.oldpassword.mismatch" ) );
				}
			}
		}
		
		return errors;
	}

	public String getAdminpassword() {
		return adminpassword;
	}

	public String getNewpassword() {
		return newpassword;
	}

	public String getRepassword() {
		return repassword;
	}

	public String getRedirect() {
	    return redirect;
	}
	
	public String getRedirectPath() {
	    return "/editUser.do?initialize=true&userId=" + getUserId() + "&redirect=" + getRedirect();
	}

	public Integer getUserId() {
		return userId;
	}

	public UserInfo getUserInfo() throws DBException {
	    return VKCUserSerializer.retrieveUserInfo( getUserId() );
	}
	
	public boolean isPasswordChanged() {
		return passwordChanged;
	}

	public void setAdminpassword( String s ) {
		adminpassword = StringUtils.normalize( s );
	}

	public void setNewpassword( String s ) {
		newpassword = StringUtils.normalize( s );
	}

	public void setPasswordChanged( boolean b ) {
		passwordChanged = b;
	}

	public void setRepassword( String s ) {
		repassword = StringUtils.normalize( s );
	}

	public void setRedirect( String s ) {
	    redirect = StringUtils.normalize( s );
	}
	
	public void setUserId( Integer i ) {
		userId = i;
	}
}
