/**
 * License Agreement.
 *
 *  JBoss RichFaces - Ajax4jsf Component Library
 *
 * Copyright (C) 2007  Exadel, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1 as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
 */
package org.richfaces.realworld.service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.richfaces.realworld.domain.Comment;
import org.richfaces.realworld.domain.Image;
import org.richfaces.realworld.domain.MetaTag;

@Name("imageAction")
@Stateless
@AutoCreate
public class ImageAction implements IImageAction {

    @In(value = "entityManager")
    EntityManager em;
    
    @In FlushStrategy flushStrategy;

    public void deleteImage(Image image) {
    	if(image.getAlbum().getCoveringImage().equals(image)){
    		image.getAlbum().setCoveringImage(null);
    	}
        image.getAlbum().removeImage(image);
        if (flushStrategy.isDatabaseStoreStrategy()) {
            em.flush();
        }
    }

    public void editImage(Image image) {
        List<MetaTag> removals = new ArrayList<MetaTag>(image.getImageTags());
        String[] tokens = image.getMetaString().split(",");
        Set<String> toks = new HashSet<String>();
        for (String s : tokens) {
            toks.add(s.trim());
        }
        for (String s : toks) {
        	MetaTag t = image.getTagByName(s);
            if (t != null) {
                	//TODO nick - how about concurrent creation of meta tags with the same name?
                removals.remove(t);
            } else {
            	t = new MetaTag();
                t.setTag(s);
                image.addMetaTag(t);
            }
        }
        for (MetaTag tag : removals) {
            image.removeMetaTag(tag);
            tag.removeImage(image);
        }
        if (image.isCovering()) {
            if (!image.equals(image.getAlbum().getCoveringImage())) {
                image.getAlbum().setCoveringImage(image);
            }
        }
        if (flushStrategy.isDatabaseStoreStrategy()) {
            em.flush();
        }
    }

    public void addImage(Image image) {
        em.persist(image);
        image.getAlbum().addImage(image);
        if (flushStrategy.isDatabaseStoreStrategy()) {
            em.flush();
        }
    }

    public void deleteComment(Comment comment) {
        comment.getImage().removeComment(comment);
        if (flushStrategy.isDatabaseStoreStrategy()) {
            em.flush();
        }
    }

    public void addComment(Comment comment) {
        comment.getImage().addComment(comment);
        if (flushStrategy.isDatabaseStoreStrategy()) {
            em.flush();
        }
    }

    public MetaTag getTagByName(String tag) {
        MetaTag t;
        try {
            t = (MetaTag) em.createQuery("from MetaTag m where m.tag =:tag").setParameter("tag", tag).getSingleResult();
        } catch (NoResultException nre) {
            return null;
        }
        return t;
    }

    public List<MetaTag> getPopularTags() {
        return em.createQuery("select new MetaTag(m.id, m.tag) from MetaTag m join m.images img group by m.id, m.tag order by count(img) desc").setMaxResults(20).getResultList();
    }

    public List<MetaTag> getTagsLikeString(String suggest) {
        return (List<MetaTag>) em.createQuery("select m from MetaTag m where lower(m.tag) like :tag").setParameter("tag", suggest + "%").getResultList();
    }
}
