package jp.ac.kyutech.mns.ist.filter;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Hashtable;

public class AvgVarCalc<E> {
	ArrayList<E> data;
	Hashtable<Integer,ArrayList<E>> hash;
	String[] mlist = {"ppd","var_ramer","pts"};
	String kn = "numrammer";
	public AvgVarCalc(){
		data = new ArrayList<E>();
		hash = new Hashtable<Integer, ArrayList<E>>();
	}
	public void add(E d){
		data.add(d);
		
		Field f = null;
		try {
			f = d.getClass().getField(kn);
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		}
		int k=0;
		try {
			k = f.getInt(d);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		ArrayList<E> ha = hash.get(k);
		if (ha == null){
			ha = new ArrayList<E>();
			hash.put(k,ha);
		}
		ha.add(d);
		
	}
	public void print(){
		for(int k: hash.keySet()){
			ArrayList<E> hashary = hash.get(k);
			if (hashary.size()<10) continue;
			System.out.println(kn + " = "+k);
			double[] avg = new double[mlist.length];
			double[] var = new double[mlist.length];
			double[] cnt = new double[mlist.length];
			int m = 0;
			for(String s: mlist){
				Field f = null;
				try {
					f = hashary.get(0).getClass().getField(s);
				} catch (NoSuchFieldException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (SecurityException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				
				double[] raw = new double[hashary.size()];
				double sum = 0;
				int i = 0;
				for(E d: hashary){
					try {
						raw[i] = f.getDouble(d);
						sum += raw[i];
					} catch (IllegalArgumentException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					i++;
				}
				//ここで，ようやくデータが揃った
				avg[m] = sum/hashary.size();
				cnt[m] = hashary.size();
				var[m] = 0;
				for(i=0;i<cnt[m];i++){
					var[m] += (avg[m]-raw[i])*(avg[m]-raw[i]);
				}
				var[m] /= cnt[m];
				System.out.print(s+"  ");
				System.out.println("Avg = "+avg[m]+"   Var = "+var[m]+"   Cnt = "+cnt[m]);
			}
			
		}
		System.out.println("");
	}
}
