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

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

import jp.hasc.hasctool.core.runtime.RuntimeContext;

/**
 * テーブルを対象としたカウントクラス
 * 指定した項目についてファイル数をカウント
 * 単一の情報のみ指定可
 * @author hiro
 */

public class ElementCounter extends TableCounter{

	boolean start_ = true;
	HashMap<String, Integer> hmap_;
	String element_;
	int count_ = 0;
	int index_;

	@Override
	public void setup(RuntimeContext context) {
		super.setup(context);
		hmap_ = new HashMap<String, Integer>();
	}

	@Override
	void count(String line) {
		String[] val = line.split(",");
		if(start_){
			for(int i = 0; i<val.length; i++){
				if(val[i].equals(element_)){
					index_ = i;
				}
			}		
			start_ = false;
		} else {
			count_++;
			int count = 1;
			if(hmap_.get(val[index_]) != null){
				count = hmap_.get(val[index_]);
				count++;
			}
			hmap_.put(val[index_], count);
		}
	}

	@Override
	String getResult() {
		String crlf = System.getProperty("line.separator");
		Iterator<String> it = hmap_.keySet().iterator();
		String row = element_ + "," + count_ + crlf;
		while (it.hasNext()) {
			String key = (String) it.next();
			int count =  hmap_.get(key);
			row += key + "," + count;
			row += crlf;
		}
		return row;
	}

	public void setElement(String element){
		element_ = element;
	}
}
