package de.hsadmin.core.model;


public class EntitySessionHelper {

	/**
	 *  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) {
		AbstractModuleImpl impl = null;
		try {
			Class<?> wrapperClass = determineModuleImpl(entityClass);
			impl = instantiateModuleImpl(tx, wrapperClass);
		} catch (ClassNotFoundException exc) {
			impl = new SecureDefaultModuleImpl();
			impl.construct(tx);
		} catch (Exception exc) {
			throw new RuntimeException(exc);
		}
		return impl;
	}

	private static AbstractModuleImpl instantiateModuleImpl(Transaction tx, Class<?> wrapperClass) 
			throws InstantiationException, IllegalAccessException {
		AbstractModuleImpl impl;
		impl = (AbstractModuleImpl) wrapperClass.newInstance();
		impl.construct(tx);
		return impl;
	}

	private static Class<?> determineModuleImpl(Class<? extends AbstractEntity> entityClass)
			throws ClassNotFoundException {
		AnnModuleImpl wrapperAnnot = entityClass.getAnnotation(AnnModuleImpl.class);
		Class<?> wrapperClass = null;
		if (wrapperAnnot != null) {
			wrapperClass = wrapperAnnot.value();
		} else {
			wrapperClass = Class.forName(entityClass.getCanonicalName() + "ModuleImpl");
		}
		return wrapperClass;
	}

}
