package org.richfaces.realworld.service;

import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Destroy;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.annotations.Scope;
import org.richfaces.realworld.domain.Album;
import org.richfaces.realworld.domain.Comment;
import org.richfaces.realworld.domain.Image;
import org.richfaces.realworld.domain.User;

@Stateful
@Name("userAction")
public class UserAction implements IUserAction {
	
	@PersistenceContext(unitName = "realworld", type=PersistenceContextType.EXTENDED)
	EntityManager em;
	
	@In(create = true, required = true) @Out
	private User user;

	public boolean login(String username, String password) {
		 user = (User)em.createQuery("from User u where u.login = :username and u.password = :password")
		.setParameter("username", username)
		.setParameter("password", password)
		.getSingleResult();
		 return user != null;
	}
	
	@Remove
	public void remove(){
		
	}
	
	@Destroy
	public void destroy(){
		
	}

	public void register(User user) {
		em.persist(user);
		this.user = user;
	}
	
	public void updateUser(User user) {
		em.merge(user);
		em.flush();
		this.user = user;
	}
	
	public void resetUser(User user) {
		em.refresh(user);
		em.flush();
		this.user = user;
	}

	public boolean isUserExist(String login) {
		try{
		User tempuser = (User)em.createQuery("from User u where u.login = :login")
		.setParameter("login", login)
		.getSingleResult();
		}catch(Exception e){
			return false;
		}
		return true;
	}
}