package org.yacos.core.forum;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.UserTransaction;
import org.yacos.core.article.Article;
import org.yacos.core.users.User;

@Stateless
@TransactionManagement(TransactionManagementType.BEAN)
public class MessageManagerBean implements IMessageManager, Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -2669902949630827480L;

	@PersistenceContext
	EntityManager em;
	@Resource
	UserTransaction ut;

	public Message addMessage(String message, String title, Integer articleId, String userLogin) {
		try {
			ut.begin();
			Message m = new Message();
			m.setMessage(message);
			m.setTitle(title);
			m.setDateMessage(new Date());
			User user = em.find(User.class, userLogin);
			m.setUser(user);
			Article a = em.find(Article.class, articleId);
			m.setArticle(a);
			em.persist(m);
			ut.commit();

			return m;
		} catch (Exception e) {
			try {
				ut.rollback();
				e.printStackTrace();
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	public List<Message> getMessagesForArticle(Integer articleId) {
		Article a = em.find(Article.class, articleId);
		Query query = em.createQuery("from Message m WHERE article = ? ORDER BY m.id DESC");
		query.setParameter(1, a);
		return query.getResultList();
	}
}
