package isrp.viewbeans;

import isrp.hibernate.model.businessobject.User;
import isrp.model.service.UserService;
import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import com.sun.faces.util.MessageFactory;

/**Komponent wsparcia dla
 * autentykacji użytkowników 
 * oraz operacji wylogowania z systemu.
 *
 */
public class AuthenticationBean implements Serializable {
	
	private static final long serialVersionUID = 1L;
	public static final String LOGIN_FAILED = "login.faild";
	private VisitBean visitBean;
	private String email;
	private String password;
	private UtilBean utilBean;

	public String login() {
		FacesContext ctx = FacesContext.getCurrentInstance();
		if (utilBean == null) utilBean=(UtilBean)ctx.getApplication().evaluateExpressionGet(ctx, "#{utilBean}", UtilBean.class);
		if (visitBean == null) visitBean=(VisitBean)ctx.getApplication().evaluateExpressionGet(ctx, "#{visitBean}", VisitBean.class);
		UserService userSer = utilBean.getServiceLocator().getUserService();
		User user = userSer.authenticate(email, password);
		if (user != null) {

			visitBean.setAuthenticationBean(this);

			visitBean.setUser(user);

			return "login_success";
		} else {
			FacesContext context = FacesContext.getCurrentInstance();
			FacesMessage errMsg = MessageFactory.getMessage(context,
					LOGIN_FAILED);
			context.addMessage(null, errMsg);
			return null;
		}
	}

	public String logout() {
		visitBean.setUser(null);
		FacesContext facesContext = FacesContext.getCurrentInstance();
		HttpSession session = (HttpSession) facesContext.getExternalContext()
				.getSession(false);
		if (session != null) {
			session.invalidate();
		}
		return "logout_success";
	}

	public VisitBean getVisitBean() {
		return visitBean;
	}

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

	public AuthenticationBean() {

	}

	public String getEmail() {
		return email;
	}

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

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

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

	public UtilBean getUtilBean() {
		return utilBean;
	}

}
