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

import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;

import org.jdom2.Element;

import com.etixpert.evolution.app.bonus.BonusData;
import com.etixpert.evolution.app.bonus.Handler;
import com.etixpert.evolution.event.Event;
import com.etixpert.evolution.event.PropagateEvent;
import com.etixpert.evolution.value.bonus.BonusDefinitionValue;

public class DifferentialBonus implements Handler {
	private Map values;
	
	public DifferentialBonus(BonusDefinitionValue src) {
		values = new Hashtable();

		// Format is to1:from11=factor11,from12=factor12,...;to2:from21=...
		String[] rowitems = src.getData().split(";");
		for (int i = 0; i < rowitems.length; i++) {
			String[] name_sect = rowitems[i].split(":");
			Map entries = new Hashtable();
			values.put(BonusDefinitionValue.getLevel(name_sect[0]), entries);
			if (name_sect.length > 1) {
				String[] items = name_sect[1].split(",");
				for (int j = 0; j < items.length; j++) {
					String[] name_val = items[j].split("=");
					entries.put(BonusDefinitionValue.getLevel(name_val[0]), new Double(name_val[1]));
				}
			}
		}
	}

	/* (non-Javadoc)
	 * @see com.etixpert.evolution.app.bonus.Handler#handle(com.etixpert.evolution.common.Event, java.util.Map)
	 */
	public boolean handle(Event event, Map environment) {
		BonusData dhv = BonusData.get(event.getEventTarget(), event.getEventDate());
		PropagateEvent order = (PropagateEvent) event; 
		Map row = (Map) values.get(order.getEventTargetLevelId());
		if (row == null) {
			row = (Map) values.get("");
		}
		if (row != null) {
			Double val = (Double) row.get(order.getFrom().getLevelId());
			if (val == null) {
				val = (Double) row.get("");
			}
			if (val != null) {
				dhv.addToDifferentialBonus(order.getBonus() * val.doubleValue() * .01);
				System.err.println("DiffBonus:" + event.getEventTarget().getId() + "," + event.getEventTargetLevelId() + "(" + order.getFrom().getLevelId() + ") " + val.doubleValue() + "*" + order.getBonus());
			}
		}
		return true;
	}
	
	public void toXML(Element e) {
		for (Iterator it = e.getChildren().iterator(); it.hasNext();) {
			Element item = (Element) it.next();
			Object levelId = BonusDefinitionValue.getLevelInt(item.getAttributeValue("Id"));
			Map row = (Map) values.get(levelId);
			if (row == null) {
				row = (Map) values.get("");
			}
			if (row != null) {
				for (Iterator it2 = row.keySet().iterator(); it2.hasNext(); ) {
					Object level = it2.next();
					Element newElement = new Element("DB");
					Double val = (Double) row.get(level);
					newElement.setAttribute("From", level.toString());
					newElement.setAttribute("value", "" + val.doubleValue());
					item.addContent(newElement);
				}
			}
		}
	}
}
