/*
 * This file is part of the DistSim distributed simulation framework (hibernate-extension)
 * Copyright (C) 2007 Ulf Hermann; 2003-2006 Doug Currie, doug.currie@alum.mit.edu and others
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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 brn.distsim.ormapper.util;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import org.hibernate.EmptyInterceptor;
import org.hibernate.EntityMode;
import org.hibernate.tuple.DynamicMapInstantiator;
import org.hibernate.type.Type;

public class Interceptor extends EmptyInterceptor {

	private static final long serialVersionUID = -2342657447441662045L;

	private Map factories = new HashMap();
	
	private boolean doDirtyCheck = true;

	/**
	 * findDirty always returns int[0] because we always take snapshots and
	 * never update contents of the database.
	 */
	public int[] findDirty(Object entity, Serializable id,
			Object[] currentState, Object[] previousState,
			String[] propertyNames, Type[] types) {
		if (doDirtyCheck)
			return null;
		else
			return new int[0];
	}

	public void setDoDirtyCheck(boolean b) {
		doDirtyCheck = b;
	}
	
	public String getEntityName(Object object) {
		String entity = null;
		if (object instanceof Map) {
			entity = (String) ((Map) object).get(DynamicMapInstantiator.KEY);
			if (entity == null) {
				entity = object.getClass().getName(); // don't throw an
				// exception here
			}
		}
		return entity;
	}

	public Object instantiate(String entityName, EntityMode entityMode,
			Serializable id) {
		Class c = null;
		Factory f = null;
		try {
			c = Class.forName(entityName);
			f = (Factory) factories.get(c);
		} catch (ClassNotFoundException e) {
			// ignore
		}
		if (f != null)
			return f.create(c);
		else
			return null;
	}

	public void registerFactory(Class c, Factory f) {
		factories.put(c, f);
	}

};
