/*
 * PersonalBonus.java
 * Created on May 17, 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.DistributorValue;
import com.etixpert.evolution.value.bonus.BonusDefinitionValue;

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

		// Format is level1=factor1,level2=factor2,...
		String[] items = src.getData().split(",");
		for (int j = 0; j < items.length; j++) {
			String[] name_val = items[j].split("=");
			values.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 ) {
		PropagateEvent propagateEvent = (PropagateEvent) event;
		DistributorValue dv = event.getEventTarget();
		if (dv.equals(propagateEvent.getOrderer())) {
			while (dv != null) {
				Double val = (Double) values.get(dv.getLevelId());
				if (val == null) {
					val = (Double) values.get("");
				}
				double dval = val != null ? val.doubleValue() : 0;
				if (dval > 0) {
					BonusData bd = BonusData.get(dv, event.getEventDate());
					bd.addToPersonalBonus(propagateEvent.getBonus() * dval * .01);
					System.err.println("PersonalBonus:" + dv.getId() + "(" + propagateEvent.getEventTarget().getId() + ")," + dval + "," + propagateEvent.getBonus());
					break;
				}
				dv = dv.getSponsor();
			}
		}
		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"));
			Double val = (Double) values.get(levelId);
			if (val == null) {
				val = (Double) values.get("");
			}
			if (val != null) {
				Element newElement = new Element("PB");
				newElement.setAttribute("value", "" + val.doubleValue());
				item.addContent(newElement);
			}
		}
	}
}
