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

	boolean start_ = true;
	String filePath_;
	int labelNum = 200;//ラベル数
	LabelData[] ldArray_ = new LabelData[labelNum];
	int index_ = 0;
	LabelData ld_;


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

	void addLabelInf(double time, String label) throws InterruptedException{
		if(ld_.getStart() < 0){
			if(!(label.equals(""))){
				ld_.setStart(time);
				ld_.setEnd(time);
				ld_.setLabel(label);
			}
		} else {
			if(label.equals(ld_.getLabel())){
				ld_.setEnd(time);
			} else {
				outputMessage(
						ld_.getStart()+","+ld_.getEnd()+","+ld_.getLabel());
				if(label.equals("")){
					ld_ = new LabelData(-1.0, -1.0, null);
				} else {
					ld_ = new LabelData(time, -1.0, label);
				}
			}
		}
	}

	@Override
	public void processMessage(Object message) throws InterruptedException {
		if (message instanceof String) {
			String line =(String)message;
			if(start_){
				outputMessage(line);
				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]);
				ldArray_[index_] = new LabelData(start,end,row[2]);
				index_++;
			}

		} else if (message == EnumCommand.END) {
			ld_ = new LabelData(-1.0, -1.0, null);
			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 = ldArray_[i].getStart();
							double end = ldArray_[i].getEnd();
							if(start <= time && time <= end){
								if(!(label.equals("")))label += "-";
								label +=  ldArray_[i].getLabel();
							}
						}
						addLabelInf(time, label);
					}
				}
				bufferedReader.close();
				inps.close();
			} catch (IOException ex) {
				CoreUtil.throwAsRuntimeException(ex);
			} catch (RuntimeException ex) {
			}
			outputMessage(EnumCommand.END);

		} else {
			//BEGIN message
			outputMessage(message);
		}
	}
}
