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.Out;
import org.richfaces.realworld.domain.Album;
import org.richfaces.realworld.domain.Comment;
import org.richfaces.realworld.domain.Image;
import org.richfaces.realworld.domain.User;

@Name("imageAction")
public class ImageAction implements IImageAction {
	//@PersistenceContext(unitName = "entityManager", type=PersistenceContextType.EXTENDED)
	@In(value="entityManager")
	EntityManager em;
	
	/* (non-Javadoc)
	 * @see org.richfaces.realworld.service.IImageAction#deleteImage(org.richfaces.realworld.domain.Image)
	 */
	public void deleteImage(Image image){
		image.getAlbum().removeImage(image);
		em.flush();
	}
	
	/* (non-Javadoc)
	 * @see org.richfaces.realworld.service.IAlbumAction#remove()
	 */
	/* (non-Javadoc)
	 * @see org.richfaces.realworld.service.IImageAction#remove()
	 */
	@Remove
	public void remove(){
		
	}
	
	/* (non-Javadoc)
	 * @see org.richfaces.realworld.service.IAlbumAction#destroy()
	 */
	/* (non-Javadoc)
	 * @see org.richfaces.realworld.service.IImageAction#destroy()
	 */
	@Destroy
	public void destroy(){
		
	}

	public void editImage(Image image, boolean parentChanged) {
		image = em.merge(image);
		if(parentChanged){
			Album albumPrevious = image.getAlbum();
			String login = albumPrevious.getOwner().getLogin();
			String albumName = image.getAlbumName();
			albumPrevious.removeImage(image);
			Album album = (Album)em.createQuery("from Album a where a.name=:albumName and a.owner.login=:login").setParameter("albumName", albumName).setParameter("login", login).getSingleResult();
			album.addImage(image);
		}
		em.flush();
	}

	public void addImage(Image image) {
		em.persist(image);
		image.getAlbum().addImage(image);
		em.flush();
	}
	
	public void deleteComment(Comment comment){
		comment.getImage().removeComment(comment);
		em.flush();
	}
	
	public void addComment(Comment comment){
		comment.getImage().addComment(comment);
		em.flush();
	}

	public void editComment(Comment comment) {
		em.merge(comment);
		em.flush();
	}

	public void vote(Image image, Long value) {
		image = em.merge(image);
		Long total = image.getRank().getTotal();
		Long votes = image.getRank().getHits();
		total += value;
		votes++;
		image.getRank().setHits(votes);
		image.getRank().setTotal(total);
		em.flush();
	}
}
