package jp.hasc.hasctool.core.runtime.filter.file.label;

import java.util.HashMap;
import java.util.Iterator;

import jp.hasc.hasctool.core.data.EnumCommand;
import jp.hasc.hasctool.core.runtime.filter.AbstractFilter;
import jp.hasc.hasctool.core.runtime.RuntimeContext;

/**
 * 計測時間をlabel毎に統合します
 * 入力データフォーマット：行動ラベル,計測時間
 * @author hiro
 */

public class LabelTimeMerger extends AbstractFilter{

	HashMap<String, Double> hmap_ = new HashMap<String, Double>();
	
	@Override
	public void setup(RuntimeContext context) {
		super.setup(context);
	}
	
	private void addTime(String line){
		String[] row = line.split(",");
		Double time = Double.parseDouble(row[1]);
		if(hmap_.get(row[0]) == null){
			hmap_.put(row[0], time);
		}else{
			time += hmap_.get(row[0]);
			hmap_.put(row[0], time);	
		}
	}

	@Override
	public void processMessage(Object message) throws InterruptedException {
		if (message instanceof String) {
			String line =(String)message;
			addTime(line);
		} else if (message == EnumCommand.END) {
			Iterator<String> it = hmap_.keySet().iterator();
			while (it.hasNext()) {
				String key = (String) it.next();
				double time =  hmap_.get(key);
				outputMessage(key + "," + time);
			}
			outputMessage(EnumCommand.END);
		} else {
			//BEGIN message
			outputMessage(message);
		}
	}

}
