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

package hu.nir.nmail.ejb.stateless;

import hu.nir.nmail.ejb.entity.EmailAddress;
import hu.nir.nmail.ejb.entity.NmailUser;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author attila
 */
@Stateless
public class NmailUserManagerBean implements NmailUserManagerRemote, NmailUserManagerLocal {
    @PersistenceContext(unitName="nmailPU")
    private EntityManager em;
    
    public NmailUser getNmailUser(Long userId) {
        Query query = em.createNamedQuery("NmailUser.findByUserId");
        query.setParameter("userId", userId);
        try {
            Object queryResult = query.getSingleResult();
            return (NmailUser) queryResult;
        } catch (NoResultException e) {
            return null;
        }
    }
    
    public List<NmailUser> getAllNmailUser() {
        Query query = em.createNamedQuery("NmailUser.findAll");
        try {
            @SuppressWarnings("unchecked")
            List<NmailUser> resultList = query.getResultList();
            return resultList;
        } catch (NoResultException e) {
            return new ArrayList<NmailUser>();
        }
    }

    public void persist(NmailUser nmailUser) {
        em.persist(nmailUser);
    }
    
    public void update(NmailUser nmailUser) {
        em.merge(nmailUser);
    }
    
    public void remove(NmailUser nmailUser) {
        em.remove(nmailUser);
    }

    public void refresh(NmailUser nmailUser) {
        em.refresh(nmailUser);
    }
    
    @SuppressWarnings("unchecked")
    public List<EmailAddress> getEmailAddresses(NmailUser nmailUser) {
        Query query = em.createNamedQuery("EmailAddress.findByUserId");
        query.setParameter("userId", nmailUser);
        List resultList = query.getResultList();
        
        return resultList;
    }
    
}
