package it.mice.voila.runtime.hibernate.interceptor;

import it.mice.voila.runtime.entity.Entity;

import java.util.Iterator;

import org.hibernate.EmptyInterceptor;
import org.hibernate.SessionFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;


/**
 * Created by IntelliJ IDEA.
 * User: zzy9v4
 * Date: 23-feb-2007
 * Time: 10.39.27
 * To change this template use File | Settings | File Templates.
 */
public class CustomInterceptor extends EmptyInterceptor implements BeanFactoryAware {
    /**
	 * 
	 */
	private static final long serialVersionUID = -8731771375437963623L;
	private BeanFactory beanFactory;
    private SessionFactory sessionFactory;

    public SessionFactory getSessionFactory() {
        if (sessionFactory == null) {
            sessionFactory = beanFactory.getBean(SessionFactory.class);
        }
        return sessionFactory;
    }

    /**
     * Called to distinguish between transient and detached entities. The return value determines the
     * state of the entity with respect to the current session.
     * <ul>
     * <li><tt>Boolean.TRUE</tt> - the entity is transient
     * <li><tt>Boolean.FALSE</tt> - the entity is detached
     * <li><tt>null</tt> - Hibernate uses the <tt>unsaved-value</tt> mapping and other heuristics to
     * determine if the object is unsaved
     * </ul>
     *
     * @param entity a transient or detached entity
     * @return Boolean or <tt>null</tt> to choose default behaviour
     */
    public Boolean isTransient(Object entity) {
        if (entity instanceof Entity) {
            Entity jfEntity = (Entity) entity;
            if (jfEntity.isNewEntity()) {
                return null;
            } else {
                return Boolean.FALSE;
            }
        }
        return super.isTransient(entity);
    }

    public void postFlush(Iterator iterator) {
    	while (iterator.hasNext()) {
			Object element = (Object) iterator.next();
			if (element instanceof Entity) {
	            Entity jfEntity = (Entity) element;
	            if (jfEntity.isChangedEntity() || jfEntity.isNewEntity()) {
		            jfEntity.setInternalEntityStateToLoaded();
	            }
			}
		}
		super.postFlush(iterator);
	}

	public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }
}
