/*
 * CreditCard.java
 * Created on Aug 25, 2005 
 * Author: 	László Felföldi, Etixpert GmbH
 * mail:	laszlo.felfoldi@etixpert.com		
 */
package com.etixpert.evolution.value.bonus;

import java.sql.Connection;
import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.etixpert.evolution.ObjectSearch;
import com.etixpert.evolution.PersistableObject;
import com.etixpert.evolution.app.bonus.BonusList;
import com.etixpert.evolution.value.DistributorValue;
import com.etixpert.evolution.value.Value;


public class BonusMetrics extends Value {
	private DistributorHistoryValue history;
	private String metric;
	private double value;
	
	public BonusMetrics(DistributorHistoryValue aHistory, String aMetric, double aValue) {
		history = aHistory;
		metric  = aMetric;
		value   = aValue;
	}
		
	public void insert(Connection conn) throws Exception {
		PersistableObject po = new PersistableObject("bonus_metrics", new LinkedList());
		po.set("distr_hist_id", history.getId());
		po.set("metric", metric);
		po.set("data", new Double(value));
		po.insert(conn);
	}
	
	public static void load(Connection conn, Date month, Map environment) {
	    ObjectSearch os = new ObjectSearch();

	    Date smonth = BonusList.getMonthBegin(month).getTime();
	    Calendar eCal = Calendar.getInstance();
	    eCal.setTime(smonth);
	    eCal.add(Calendar.MONTH, 1);
	    Date emonth = eCal.getTime();
	    
	    try {
	        List items = os.search(conn, 
	            "Select * From " +
	            "bonus_metrics m Join distributor_history h On m.distr_hist_id=h.distr_hist_id " +
	            "Where h.level_to = ?",
                new Object[] {new java.sql.Date(emonth.getTime() - 1)} 
	        );
	        
	        for (Iterator it = items.iterator(); it.hasNext(); ) {
	            PersistableObject po = (PersistableObject) it.next();
	            DistributorValue dv = (DistributorValue) environment.get(po.get("distr_id"));
	            
	            if (dv != null) {
	                dv.setAuxMetric((String) po.get("metric"), po.get("data"));
	            }
	        }
	        
	    } catch (Exception e) {
	        e.printStackTrace(System.err);
	    }
	}
}
