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

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

/**
 * ラベルファイルを編集するフィルタです
 * 同じラベル情報が連続した場合、それらの行を統合します
 * 入力データフォーマット：startTime,endTime,label
 * @author hiro
 */

public class LabelLineMerger extends AbstractFilter{

	String[][] LabelData_;
	int index_;
	int lineNum_ = 5000;
	boolean lineStart_ = true;
	boolean dataStart_ = true;

	@Override
	public void setup(RuntimeContext context) {
		super.setup(context);
		index_ = 0;
		LabelData_ = new String[lineNum_][3];
	}

	private void setLabelInf(String line){
		String[] row = line.split(",");
		//row[0]:startTime, row[1]:endTime, row[2]:label
		if(dataStart_ == true){
			LabelData_[index_][0] = row[0];
			LabelData_[index_][1] = row[1];
			LabelData_[index_][2] = row[2];
			dataStart_ = false;
		}
		
		//endTimeの上書き
		if(LabelData_[index_][2].equals(row[2])){
			LabelData_[index_][1] = row[1];
		} else {
			index_++;
			LabelData_[index_][0] = row[0];
			LabelData_[index_][1] = row[1];
			LabelData_[index_][2] = row[2];
		}
		if(lineNum_<index_)System.out.println("Too many Labels");
	}

	@Override
	public void processMessage(Object message) throws InterruptedException {
		if (message instanceof String) {
			String line =(String)message;
			if(lineStart_){
				outputMessage(line);
				lineStart_ = false;
			} else {
				setLabelInf(line);
			}
		} else if (message == EnumCommand.END) {
			for(int i=0; i<index_+1; i++){
				outputMessage(LabelData_[i][0]+","+LabelData_[i][1]+","+LabelData_[i][2]);		
			}
			outputMessage(EnumCommand.END);
		} else {
			//BEGIN message
			outputMessage(message);
		}
	}

}
