package isrp.viewbeans;


import isrp.hibernate.model.businessobject.User;
import isrp.hibernate.model.util.Md5HashCode;
import isrp.model.service.UserService;
import isrp.utils.IsrpUtils;
import isrp.utils.MessageUtil;

import java.io.Serializable;

import javax.faces.context.FacesContext;


/** Komponent wsparcia dla operacji odzyskiwania hasła przez użytkownika.
 *
 */
public class ForgotPasswordBean implements Serializable {

	private static final long serialVersionUID = 1L;
	private String email;
	private VisitBean visitBean;
	private UtilBean utilBean;
	
	public String getNewPassword(){
		//
		FacesContext faces = FacesContext.getCurrentInstance();
		if (utilBean == null) utilBean=(UtilBean)faces.getApplication().evaluateExpressionGet(faces, "#{utilBean}", UtilBean.class);
		UserService userSer = utilBean.getServiceLocator().getUserService();
		User user = userSer.checkIfEmailExistInDB(email);
		if (user != null){
						           
			String pass =IsrpUtils.generateNewPassword(email);
            String passMd5 = Md5HashCode.getMd5HashCode(pass);     
            user.setPassword(passMd5);
            userSer.saveNewPassword(user,pass,utilBean.getEmailConfiguration());                      
            
            MessageUtil.addMessageToContext(faces, "forgotPassword.message.success");
			email=null;
			return null;
		}else{			
			MessageUtil.addMessageToContext(faces, "forgotPassword.message.error");
			return null;
		}			
	}
	
	public UtilBean getUtilBean() {
		return utilBean;
	}

	public void setUtilBean(UtilBean utilBean) {
		this.utilBean = utilBean;
	}

	public VisitBean getVisitBean() {
		return visitBean;
	}



	public void setVisitBean(VisitBean visitBean) {
		this.visitBean = visitBean;
	}



	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}
	

}
