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;

@Stateful
@Name("imageAction")
public class ImageAction implements IImageAction {
	@PersistenceContext(unitName = "realworld", type=PersistenceContextType.EXTENDED)
	EntityManager em;

	/* (non-Javadoc)
	 * @see org.richfaces.realworld.service.IAlbumAction#addAlbum()
	 */
	/* (non-Javadoc)
	 * @see org.richfaces.realworld.service.IImageAction#addAlbum(org.richfaces.realworld.domain.Album)
	 */
	public void addAlbum(Album album) {
		//em.persist(album);
		//user.addAlbum(album);
		//em.flush();
	}
	
	/* (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) {
		em.merge(image);
		if(parentChanged){
			String login = image.getAlbum().getOwner().getLogin();
			String albumName = image.getAlbumName();
			image.getAlbum().removeImage(image);
			Album album = (Album)em.createQuery("from Album a where a.name=:albumName and a.owner.name=:login").setParameter("albumName", albumName).setParameter("owner", login).getSingleResult();
			album.addImage(image);
			em.merge(album);
		}
		em.flush();
	}

	public void addImage(Image image) {
		em.persist(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();
	}
}
