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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import jp.hasc.hasctool.core.runtime.filter.AbstractFilter;
import jp.hasc.hasctool.core.data.EnumCommand;
import jp.hasc.hasctool.core.runtime.RuntimeContext;
import jp.hasc.hasctool.core.util.CoreUtil;

/**
 * データ量（行）をカウントします
 * @author hiro
 */
public class LineCounter extends AbstractFilter{

	private int count_=0;

	@Override
	public void processMessage(Object message) throws InterruptedException {
		if (message instanceof String) {
			String s =(String)message;
			count(s);
		} else if (message == EnumCommand.END) {
			outputMessage("Number of Data:"+count_);
			outputMessage(EnumCommand.END);
		} else {
			//BEGIN message
			outputMessage(message);
		}
	}

	private void count(String filePath){
		try{
			InputStream inps = getRuntimeContext().getFileStreamProvider().openInputStream(filePath);
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inps, RuntimeContext.DEFAULT_CHARSET));
			int c = 0;
			while(true){
				String line = bufferedReader.readLine();
				if (line == null) {
					break;
				} else {
					c++;
				}
			}
			bufferedReader.close();
			inps.close();
			try {
				outputMessage(filePath+":"+c);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			count_ += c;
		} catch (IOException ex) {
			CoreUtil.throwAsRuntimeException(ex);
		} catch (RuntimeException ex) {
		}
	}
}
