package org.richfaces.realworld.service;

import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;

import org.jboss.seam.annotations.Destroy;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.TransactionPropagationType;
import org.jboss.seam.annotations.Transactional;
import org.richfaces.realworld.domain.Comment;
import org.richfaces.realworld.domain.Message;
import org.richfaces.realworld.domain.User;

@Name("messageAction")
public class MessageAction implements IMessageAction {
	//@PersistenceContext(unitName = "entityManager", type=PersistenceContextType.EXTENDED)
	@In(value="entityManager")
	EntityManager em;
	
	/* (non-Javadoc)
	 * @see org.richfaces.realworld.service.IMessageAction#sendMessage(org.richfaces.realworld.domain.Message)
	 */
	@Transactional(TransactionPropagationType.REQUIRED)
	public void sendMessage(Message message){
		if(message.getOwnerLogin() != null){
			User user = (User)em.createQuery("from User u where u.login = :login")
			.setParameter("login", message.getOwnerLogin())
			.getSingleResult();
			message.setOwner(user);
			message.setOwnerLogin(null);
		}
		if(message.isFriendshipRequest()){
			message.getAuthor().addFriendshipRequest(message.getOwner());
		}
		em.persist(message);
		em.flush();
	}
	
	/* (non-Javadoc)
	 * @see org.richfaces.realworld.service.IMessageAction#deleteMessage(org.richfaces.realworld.domain.Message)
	 */
	@Transactional(TransactionPropagationType.REQUIRED)
	public void deleteMessage(Message message){
		//message = em.merge(message);
		//em.remove(message);
		message.getOwner().removeMessage(message);
		em.flush();
	}
	
	public void markAsReaded(Message message){
		message.setReaded(true);
		em.flush();
	}
	/* (non-Javadoc)
	 * @see org.richfaces.realworld.service.IAlbumAction#remove()
	 */
	@Remove
	public void remove(){
		
	}
	
	/* (non-Javadoc)
	 * @see org.richfaces.realworld.service.IAlbumAction#destroy()
	 */
	@Destroy
	public void destroy(){
		
	}
}
