package org.yacos.web.system.controller;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.yacos.core.users.IUserManager;
import org.yacos.core.users.User;
import org.yacos.web.system.form.FormForgotPassword;
import org.yacos.web.system.session.YACOSUtils;

public class ForgotPasswordController extends SimpleFormController {
	private IUserManager userManager;
	
	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		String email = ((FormForgotPassword) command).getEmail();

		email = email.toLowerCase();
		Pattern emailPattern = Pattern.compile("^[a-z0-9._-]+@[a-z0-9._-]{2,}[.][a-z]{2,4}$");	// Regex
		Matcher emailMatcher = emailPattern.matcher(email);
		
		User user = null;
		if(!emailMatcher.matches()){
			errors.rejectValue("email", "form.forgotPassword.error.emailInvalid");
		} else {
		
			user = userManager.getUserByEmail(email);
			if(user == null){
			errors.rejectValue("email", "form.forgotPassword.error.unknownEmail");
			}
		}
		
		if(errors.hasErrors()){
			return showForm(request,response, errors);
		} else {
			String newPassword = YACOSUtils.generate(12);
			user.setPassword(User.hashPassword(newPassword));
			
			userManager.UpdateUser(user);
			
			String mailSubject = "Your new YACOS password";
			String mailBody = "You received this email because you requested your account informations.\n";
			mailBody += "A new password has been generated, you can now login using the following informations and change it in your profile view.\n";
			mailBody += "User login : "+user.getLogin()+"\n";
			mailBody += "User password : "+newPassword;
			
			MailSenderService.getInstance().sendEMail(email, mailSubject, mailBody);
			
			request.setAttribute("success", true);
			
			return showNewForm(request, response);
		}
	}
	
	public void setUserManager(IUserManager userManager) {
		this.userManager = userManager;
	}
	
	public IUserManager getUserManager() {
		return userManager;
	}
}
