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

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

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

/**
 * ディレクトリ別にファイル数をカウントします
 * @author hiro
 */

public class FileCounterInEachDirectory extends FileCounter{

	private int folderClass_;
	private HashMap<String, Integer> hmap_;
	private String dname_ = null;

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

	@Override
	public void processMessage(Object message) throws InterruptedException {
		if (message instanceof String) {
			String s =(String)message;
			String[] part = s.split("/");
			String dname = part[part.length - folderClass_];
			if(!(dname.equals(dname_))){
				System.out.println(dname);
				dname_ = dname;
			}
			count(dname);
		} else if (message == EnumCommand.END) {
			Iterator<String> it = hmap_.keySet().iterator();
			while (it.hasNext()) {
				String key = (String) it.next();
				int count =  hmap_.get(key);
				String row = key + "," + count;
				outputMessage(row);
			}
			System.out.println("countEnd");
			outputMessage(EnumCommand.END);
		} else {
			//BEGIN message
			outputMessage(message);
		}
	}

	private void count(String key){
		if((hmap_.containsKey(key))){
			int count = hmap_.get(key);
			count++;
			hmap_.put(key,count);
		} else {
			hmap_.put(key,1);
		}
	}

	public void setFolderClass(int folderClass){
		folderClass_ = folderClass+1;
	}
}
