package de.hsadmin.core.model;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class EntitySessionHelper {

	private static Log log = LogFactory.getLog(EntitySessionHelper.class);

	/**
	 *  helper method to create a wrapper for checking the rights according to
	 *  the entity class.
	 * @param entityClass
	 * @return
	 */
	public static AbstractModuleImpl createEntitySessionWrapper(Class<? extends AbstractEntity> entityClass, Transaction tx) {
		// get in instance
		AbstractModuleImpl impl = null;
		try {
			// determine wrapper class
			ModuleImpl wrapperAnnot = entityClass.getAnnotation(ModuleImpl.class);
			Class<?> wrapperClass = null;
			if (wrapperAnnot != null) {
				wrapperClass = wrapperAnnot.value();
			} else {
				wrapperClass = Class.forName(entityClass.getCanonicalName() + "ModuleImpl");
			}
			// instantiate wrapper
			impl = (AbstractModuleImpl) wrapperClass.newInstance();
			impl.construct(tx);
		} catch (ClassNotFoundException exc) {
			log.info("entity class '"
							+ entityClass.getCanonicalName()
							+ "' has no session wrapper => using restrictive default access rights");
			impl = new SecureDefaultModuleImpl();
			impl.construct(tx);
		} catch (Exception exc) {
			throw new RuntimeException(exc);
		}
		return impl;
	}

}
