package brn.distsim.ormapper.util;

import org.hibernate.HibernateException;
import org.hibernate.engine.Cascade;
import org.hibernate.engine.CascadingAction;
import org.hibernate.engine.EntityKey;
import org.hibernate.event.EventSource;
import org.hibernate.event.def.DefaultEvictEventListener;
import org.hibernate.persister.entity.EntityPersister;

public class EvictEventHandler extends DefaultEvictEventListener {

	private static final long serialVersionUID = 5990186248400470953L;

	protected void doEvict(final Object object, final EntityKey key,
			final EntityPersister persister, final EventSource session)
			throws HibernateException {

		// remove all collections for the entity from the session-level cache
		if (persister.hasCollections()) {
			// before evicting (and reverting) flush collections
			// takes time, but works
			//new FlushVisitor(session, object)
			//		.processEntityPropertyValues(persister.getPropertyValues(
			//				object, session.getEntityMode()), persister
			//				.getPropertyTypes());
			new EvictVisitor(session).process(object, persister);
		}

		// remove any snapshot, not really for memory management purposes, but
		// rather because it might now be stale, and there is no longer any
		// EntityEntry to take precedence
		// This is now handled by removeEntity()
		// session.getPersistenceContext().removeDatabaseSnapshot(key);

		new CascadeMap(CascadingAction.EVICT, Cascade.AFTER_EVICT, session)
				.cascade(persister, object);
	}

}
