/*
 * TradeMargin.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.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

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 TradeMargin implements Handler {
	private Set values;
	
	public TradeMargin(BonusDefinitionValue src) {
		values = new HashSet();

		// Format is level1,level2,...
		String[] items = src.getData().split(",");
		for (int j = 0; j < items.length; j++) {
			values.add(BonusDefinitionValue.getLevel(items[j]));
		}
	}
	
	/* (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())) {
			if (values.contains(dv.getLevelId())) {
				// search for a distributor who will get the bonus
				for (DistributorValue to = dv.getSponsor(); to != null && to.getLevelId() != null; to = to.getSponsor()) {
					if (!values.contains(to.getLevelId())) {
						BonusData bd = BonusData.get(to, event.getEventDate());
						double val = propagateEvent.getTradeMargin();
						bd.addToTradeMarginBonus(val);
						bd.addTobCV(propagateEvent.getBonus());
						System.err.println("TradeMargin from " + event.getEventTarget().getId() + "(" + event.getEventTarget().getLevelId() + ") to " + to.getId() + " " + val); 
						break;
					}	
				}
			}
		}
		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"));
			if (values.contains(levelId)) {
				Element newElement = new Element("TB");
				item.addContent(newElement);
			}
		}
	}
}
