/*
 * $Id: ForgotPasswordAction.java,v 1.28 2008/02/12 09:33:56 korowa Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 *
 * Revision 1.1  2003/10/30 13:52:29  marbobo
 * Initiale Version
 *
 */
package vkc.view.action;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.struts.Globals;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import vkc.db.entities.VKCUser;
import vkc.db.serializer.VKCSysParameterSerializer;
import vkc.db.serializer.VKCUserSerializer;
import vkc.exception.DBException;
import vkc.misc.MailUtils;
import vkc.misc.TemplateParser;
import vkc.misc.VKCLogManager;
import vkc.util.ServletUtils;
import vkc.util.VKCCoder;
import vkc.util.VKCStringUtils;
import vkc.view.WebShare;
import vkc.view.bean.ResourceInfo;
import vkc.view.form.ForgotPasswordForm;


public final class ForgotPasswordAction extends Action {
	private ActionForward DEFAULT_FORWARD = new ActionForward("/templates/${template.name}/common/ForgotPassword.jsp");

	public ActionForward execute( ActionMapping mapping, 
            					  ActionForm f,
            					  HttpServletRequest request, 
            					  HttpServletResponse response )
    throws Exception {
        ForgotPasswordForm form = (ForgotPasswordForm) f;

        if (request.getParameter("action.back") != null) {
			return new ActionForward(WebShare.getLoginPage(), true);
        }

        if (request.getParameter("action.send.password") != null) {
            return handleSendPasswordAction(form, request);
        }

        return DEFAULT_FORWARD;
    }

    private ActionForward handleSendPasswordAction(ForgotPasswordForm form, HttpServletRequest request)
    throws DBException, 
       	   UnsupportedEncodingException, 
       	   NoSuchAlgorithmException {
        // Hole neue Benutzerdaten aus der Form
        String username = VKCStringUtils.filterUnicodeChars(form.getUsername());

        //zufälliges MD5-Passwort erzeugen
        String password = RandomStringUtils.randomAlphanumeric(8);
        byte[] md5Bytes = (username + password).getBytes("ISO-8859-1");

        MessageDigest digest = MessageDigest.getInstance("MD5");
        digest.reset();
        digest.update(md5Bytes);

        byte[] fingerPrint = digest.digest();
        fingerPrint = VKCCoder.base64Encode(fingerPrint);

        String md5Password = new String(fingerPrint, "ISO-8859-1");

        //Benutzer holen
        VKCUser user = VKCUserSerializer.retrieveUser(username);

        user.setPassword(md5Password);
        user.setPasswordChanged(false);
        user.setLastChanged(new Timestamp(System.currentTimeMillis()));
        user.setLastChangerId(user.getUserId());

        try {
            // Neuem Benutzer die Zugangsdaten zuschicken
			String senderAddr  = VKCSysParameterSerializer.retrieveValue("MAIL", "AdminEmail", "");
			String smtpServer  = VKCSysParameterSerializer.retrieveValue("MAIL", "MailServer", "");
			String smtpUsername  = VKCSysParameterSerializer.retrieveValue("MAIL", "MailUsername", "");
			String smtpPassword  = VKCSysParameterSerializer.retrieveValue("MAIL", "MailPassword", "");
			String vkc_rootURL = WebShare.getRootURL() + WebShare.getContextPath();
            String subject     = WebShare.resources.getMessage(user.getLanguage().getLocale(), "vkc.changepassword");
            String recepient   = VKCStringUtils.decodeXmlEntities(user.getEmail());

			TemplateParser asciiTemplate = TemplateParser.getTemplateParser();
			TemplateParser htmlTemplate = TemplateParser.getTemplateParser();

			HashMap context = new HashMap();
			context.put("adminEmail", senderAddr);
			context.put("homepage", vkc_rootURL);
			context.put("username", VKCStringUtils.filterUnicodeChars(user.getUser()));
			context.put("fullname", VKCStringUtils.filterUnicodeChars(user.getFirstname() + " " + user.getLastname()));
			context.put("password", password);
			context.put("resources", new ResourceInfo(WebShare.resources, user.getLanguage().getLocale()));
			context.put("vkcstringutils", new VKCStringUtils());
			context.put("template", user.getTemplate().getName());
			
			asciiTemplate.setContextData(context);
			htmlTemplate.setContextData(context);
			String asciiPath = "templates/${template.name}/velocitytemplates/mail/changepassword_notification.plain";
			String htmlPath = "templates/${template.name}/velocitytemplates/mail/changepassword_notification.html";
			String asciiText = asciiTemplate.createString(ServletUtils.replacePathVars(asciiPath, user));
			String htmlText = htmlTemplate.createString(ServletUtils.replacePathVars(htmlPath, user));

			
			MailUtils m = new MailUtils(user);
            if(user.isEnableHtmlNotification())m.sendSMTPMailWithVKCLogo( senderAddr, recepient, subject, asciiText, htmlText, null, null, smtpServer, smtpUsername, smtpPassword );
            else m.sendSMTPMail( senderAddr, recepient, subject, asciiText,null , null, null, smtpServer, smtpUsername, smtpPassword );
        } catch (Exception e) {
            ActionErrors errors = new ActionErrors();
            errors.add("mailmessage.failure", new ActionError("vkc.administration.newuser.mailfailure"));
            request.setAttribute(Globals.ERROR_KEY, errors);
			VKCLogManager.errorLog(this, "1", " - email sending failed!", e);

            return DEFAULT_FORWARD;
        }

        // Benutzer in die Datenbank speichern
        VKCUserSerializer.saveUser(user);

        request.setAttribute(WebShare.INFO_KEY, "login.newpassword.created");

        return DEFAULT_FORWARD;
    }
}