/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package manager;

import entities.Users;
import helper.DatabaseException;
import helper.UserRole;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Szilárd
 */
@Stateless
public class UserSessionBean implements UserSessionBeanRemote {
    
    @PersistenceContext
    private EntityManager em;

    public void newUser(Users user) {
        em.persist(user);
    }

    public Users login(String name,String password) throws DatabaseException{
        List<Users> user = this.findUserByUserName(name);
        Users u;
        if(user.isEmpty())
            throw new DatabaseException("Nincs ilyen felhasználó: "+name);
        else
            if(!user.get(0).getPassword().equals(password))
                throw new DatabaseException("Hibás jelszó");
        u = user.get(0);
        return u;
    }

    public void update(Users user) {
        Query q = em.createNamedQuery("User.update");
        q.setParameter("name", user.getName());
        q.setParameter("userName", user.getUserName());
        q.setParameter("password", user.getPassword());
        q.setParameter("userRole", user.getUserRole());
        q.setParameter("userId", user.getId());
        q.executeUpdate();
    }

    public List<Users> allUser() {
        Query query = em.createNamedQuery("Users.findAll");
        return query.getResultList();
    }

    private List<Users> findUserByUserName(String userName) {
        Query q = em.createNamedQuery("Users.byUserName");
        q.setParameter("userName", userName);
        return q.getResultList();
    }

    public List<Users> findTeacher(){
        Query q = em.createNamedQuery("Users.findTeachers");
        q.setParameter("userRole", UserRole.TEACHER);
        return q.getResultList();
    }

    public Users findById(long id){
        Query q = em.createNamedQuery("Users.findById");
        q.setParameter("id", id);
        return (Users)q.getResultList().get(0);
    }
}
