/**
 * 
 */
package org.yacos.core.users;


import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.yacos.core.exceptions.PKAlreadyUsedException;

/**
 * @author christiancorsano
 *
 */
@Stateless
public class UserManagerBean implements IUserManager{
	@PersistenceContext
	EntityManager em;
	
	@SuppressWarnings("unchecked")
	public List<User> getUsers(){
		Query query = em.createNativeQuery("from User", User.class);
		return query.getResultList();
	}
	
	/**
	 * Adds a user into the system 
	 * throw PKAlreadyUsedException if login exist in the DB 
	 * @param user
	 */
	public User addUser(String login, String password, String firstName,
			String lastName, String organization, String email) throws PKAlreadyUsedException{
		
		if (!this.exists(login)){
			User user = new User(login, password, firstName, lastName, organization, email);
			em.persist(user);
			em.flush();
			return user;
		}
		else{ throw new PKAlreadyUsedException(); }
	}
	
	/**
	 * Removes a user from the system
	 * @param user
	 */
	public void removeUser(User user){
		User persistedUser = em.find(User.class, user.getLogin());
		em.remove(persistedUser);
	}

	public User getUser(String login) {
		return em.find(User.class, login);
	}
	
	public void UpdateUser(User user){
		em.merge(user);
	}
	
	public Boolean exists(String login){
	  return (this.getUser(login)!= null); 
	}

	public List<Role> getRoles() {
		// TODO Auto-generated method stub
		return null;
	}
	
}
