/*
 * Calculation.java
 * Created on May 3, 2005 
 * Author: 	L�szl� Felf�ldi, Etixpert GmbH
 * mail:	laszlo.felfoldi@etixpert.com		
 */
package com.etixpert.evolution.app.bonus;

import java.lang.reflect.Constructor;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.jdom2.Element;

import com.etixpert.evolution.event.Event;
import com.etixpert.evolution.value.bonus.BonusDefinitionValue;

public class Engine {	
	private static Map handlerCache = new Hashtable();
	
	static public void resetHandlerCache() {
		handlerCache.clear();
	}
	
	static public void handleEvent(Event event, Map environment) {
	
		// get the bonus definition list from the database
		Set bonusdefs = BonusDefinitionValue.findByEvent(event);
		// process all of them
		for (Iterator it = bonusdefs.iterator(); it.hasNext(); ) {
//			BonusDefinition bonusdef = (BonusDefinition) it.next();
//			BonusDefinitionValue bv = (BonusDefinitionValue) bonusdef.getValue();
			BonusDefinitionValue bv = (BonusDefinitionValue) it.next();
			
			try {
				// get the handler class
				Handler handler = (Handler) handlerCache.get(bv.getBonusId());
				// if there is no such entry in the cache, create it.
				if (handler == null) {
					Class handlerClass = null;
					
					try {
						handlerClass = Class.forName(bv.getClassName());
					} catch (ClassNotFoundException e) {
						handlerClass = Class.forName("com.etixpert.evolution.app.bonus.handler." + bv.getClassName());
					}
					
					Constructor ctor = handlerClass.getConstructor(new Class[] {bv.getClass()});
					handler = (Handler) ctor.newInstance(new Object[] {bv});
					
					/* 
					 * TODO: cache management
					 */ 
					handlerCache.put(bv.getBonusId(), handler);
				}
				handler.handle(event, environment);
			} catch (Exception e) {
				e.printStackTrace(System.err);
			}
		}
	}
	
	static public void toXML(Element to) {
		for (Iterator it = handlerCache.values().iterator(); it.hasNext(); ) {
			Handler handler = (Handler) it.next();
			handler.toXML(to);
		}
	}
}
