package com.myeclipseide.logon.jsf;

import java.io.Serializable;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import com.myeclipseide.logon.jpa.Users;
import com.sun.faces.context.flash.ELFlash;

@ManagedBean(name = "logonBean")
@RequestScoped
public class LogonBean implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = -3357672562777706169L;
	private static final String PERSISTENCE_UNIT_NAME = "JSFJPALoginExample";
	private static EntityManagerFactory factory;

	private String userName;
	private String password;

	public LogonBean() {

	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

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

	public String validate() {

		factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
		EntityManager em = factory.createEntityManager();
		Query q = em
				.createQuery("SELECT u FROM Users u WHERE u.login = :login AND u.password = :pass");
		q.setParameter("login", userName);
		q.setParameter("pass", password);
		q.setMaxResults(1);

		try {
			Users user = (Users) q.getSingleResult();
			if (userName.equals(user.getLogin())
					&& password.equals(user.getPassword())) {
				ELFlash.getFlash().put("name", user.getName());
				return "welcome.xhtml?faces-redirect=true";
			}
		} catch (Exception e) {
			FacesMessage msg = new FacesMessage("Invalid Login! Please register first.");
			msg.setSeverity(FacesMessage.SEVERITY_ERROR);
			FacesContext.getCurrentInstance().addMessage("loginForm", msg);
			return null;
		}

		return "login.xhtml?faces-redirect=true";
	}

	public String logout() {
		FacesContext.getCurrentInstance().getExternalContext()
				.invalidateSession();
		return "login.xhtml?faces-redirect=true";
	}

}
