/*
 * Metrics.java
 * Created on May 18, 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.Hashtable;
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.bonus.BonusDefinitionValue;

public class Metrics implements Handler {
	Map values;

	public Metrics(BonusDefinitionValue src) {
		values = new Hashtable();

		// Format is metric1=.,level1,level2,...;metric2=...     '.' means own orders
		String[] rowitems = src.getData().split(";");
		for (int i = 0; i < rowitems.length; i++) {
			String[] name_sect = rowitems[i].split("=");
			Set entries = new HashSet();
			values.put(name_sect[0], entries);
			String[] items = name_sect[1].split(",");
			for (int j = 0; j < items.length; j++) {
				entries.add(BonusDefinitionValue.getLevel(items[j]));
			}
		}
	}
	
	/* (non-Javadoc)
	 * @see com.etixpert.evolution.app.bonus.Handler#handle(=com.etixpert.evolution.event.Event)
	 */
	public boolean handle(Event event, Map environment) {
		PropagateEvent propagateEvent = (PropagateEvent) event;
		System.err.println("Metrics:" + event.getEventTarget().getId() + "," + event.getEventTarget().getLevelId() + " (" +  propagateEvent.getFrom().getLevelId() + ") "+ propagateEvent.getBonus());
		BonusData bd = BonusData.get(event.getEventTarget(), event.getEventDate());
		double point = propagateEvent.getPoint();
		double bonus = propagateEvent.getBonus();
		double price = propagateEvent.getPrice();
		

		if (bd.getDistributor().equals(propagateEvent.getOrderer())) {
			Object level = ".";
			if (((Set) values.get("PV")) .contains(level)) bd.addToPV (point, bonus, price);
			if (((Set) values.get("EV")) .contains(level)) bd.addToEV (point, bonus, price);
			if (((Set) values.get("PEV")).contains(level)) bd.addToPEV(point, bonus, price);
			if (((Set) values.get("TV")) .contains(level)) bd.addToTV (point, bonus, price);
			if (((Set) values.get("OV")) .contains(level)) bd.addToOV (point, bonus, price);
		} else {
			Object level = propagateEvent.getFrom().getLevelId();
			if (((Set) values.get("PV")) .contains(level)) bd.addToPV (point, bonus, price);
			if (((Set) values.get("EV")) .contains(level)) bd.addToEV (point, bonus, price);
			if (((Set) values.get("PEV")).contains(level)) bd.addToPEV(point, bonus, price);
			if (((Set) values.get("TV")) .contains(level)) bd.addToTV (point, bonus, price);
			if (((Set) values.get("OV")) .contains(level)) bd.addToOV (point, bonus, price);
		}
		bd.addTotOV(propagateEvent.getTradeMargin());
		return true;
	}
	
	public void toXML(Element to) {
	}
}
