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 TimeCounter extends AbstractFilter{

	private double time_=0.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("Measurement Time,"+time_);
			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));
			boolean start= true;
			double stime = 0.0;
			double etime = 0.0;
			while(true){
				String line = bufferedReader.readLine();
				if (line == null) {
					break;
				} else if(start){
					String[] val = line.split(",");
					stime = Double.parseDouble(val[0]);
					start = false;
				} else {
					String[] val = line.split(",");
					etime = Double.parseDouble(val[0]);
				}
			}
			bufferedReader.close();
			inps.close();
			double t = etime - stime;
			try {
				outputMessage(filePath+","+t);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			time_ += t;
		} catch (IOException ex) {
			CoreUtil.throwAsRuntimeException(ex);
		} catch (RuntimeException ex) {
		}
	}
}
