package web.service;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import persistence.model.Noticia;

public class NoticiaServiceImpl extends BaseService implements NoticiaService {

	public void addNoticia(Noticia noticia) {
		EntityManager em = getEntityManager();
		
		em.getTransaction().begin();
		em.persist(noticia);		
		em.getTransaction().commit();			

	}

	public Noticia findByID(long id) {
		EntityManager em = getEntityManager();		
		return em.find(Noticia.class, id);		
	}
	
	@SuppressWarnings("unchecked")
	public List<Noticia> getAllNoticias() {
		List<Noticia> noticias = new ArrayList<Noticia>();
		
		EntityManager em = getEntityManager();

		em.getTransaction().begin();
		
		Query query = em.createQuery("SELECT n FROM Noticia n");		
		noticias = query.getResultList();
		
		em.getTransaction().commit();

		return noticias;	
		
	}

	@SuppressWarnings("unchecked")
	public List<Noticia> getAllNoticiasByAssunto(Long assuntoId) {
		List<Noticia> noticias = new ArrayList<Noticia>();	
		
		EntityManager em = getEntityManager();

		em.getTransaction().begin();
		
		Query query = em.createQuery("SELECT n FROM Noticia n WHERE n.assunto.assuntoId= ?1");	
		query.setParameter(1, assuntoId);
		noticias = query.getResultList();
		
		em.getTransaction().commit();

		return noticias;
	}
}
