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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

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

/**
 * label情報を追加します
 * @author hiro
 */

public class LabelAdder extends AbstractFilter{

	boolean start_ = true;
	String filePath_;
	LabelData[] ld_ = new LabelData[200];
	int index_ = 0;

	@Override
	public void setup(RuntimeContext context) {
		super.setup(context);
	}

	@Override
	public void processMessage(Object message) throws InterruptedException {
		if (message instanceof String) {
			String line =(String)message;
			if(start_){
				String[] row = line.split(":");
				filePath_ = row[1];
				start_ = false;
			}else if(line.contains(",")){
				String[] row = line.split(",");
				double start = Double.parseDouble(row[0]);
				double end = Double.parseDouble(row[1]);
				ld_[index_] = new LabelData(start,end,row[2]);
				index_++;
			}

		} else if (message == EnumCommand.END) {
			try{
				InputStream inps = getRuntimeContext().getFileStreamProvider().openInputStream(filePath_);
				BufferedReader bufferedReader = 
					new BufferedReader(new InputStreamReader(inps, RuntimeContext.DEFAULT_CHARSET));
				while(true){
					String line = bufferedReader.readLine();
					if (line == null) {
						break;
					} else{
						String[] val = line.split(",");
						double time = Double.parseDouble(val[0]);
						String label = "";
						for(int i=0; i<index_; i++){
							double start = ld_[i].getStart();
							double end = ld_[i].getEnd();
							if(start <= time && time <= end){
								if(!(label.equals("")))label += "-";
								label +=  ld_[i].getLabel();
							}
						}
						outputMessage(line + "," + label);
					}
				}
				bufferedReader.close();
				inps.close();
			} catch (IOException ex) {
				CoreUtil.throwAsRuntimeException(ex);
			} catch (RuntimeException ex) {
			}
			outputMessage(EnumCommand.END);
		} else {
			//BEGIN message
			outputMessage(message);
		}
	}
}
