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

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

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

/**
 * LabelFile から学習用データへの変換フィルタ
 * @author hiro
 */
public class LabelToLearningDataFilter extends AbstractFilter{

	//識別対象を指定
	String labelFilePath_;
	ArrayList<LabelData> labelDList_ ;

	@Override
	public void setup(RuntimeContext context) {
		super.setup(context);
		labelDList_ = new ArrayList<LabelData>();
	}

	private void setLabelData(String[] input, ArrayList<LabelData> labelList) {
		int len = input.length;
		if(len == 3){
			LabelData ld = new LabelData();
			ld.setTime(Double.parseDouble(input[0]), Double.parseDouble(input[1]));
			ld.setLabel(input[2]);
			labelList.add(ld);
		}
	}

	public void processMessage(Object message) throws InterruptedException {
		if (message instanceof String) {
			String s = (String)message;
			String[] val = s.split(",");
			String element = null;
			double time = Double.parseDouble(val[0]);

			for(int i=0; i<labelDList_.size(); i++){
				LabelData ld = labelDList_.get(i);
				double start = ld.getStartTime();
				double end = ld.getEndTime();
				if (start<time && time<end){
					element = ld.getLabel();
					break;
				}
			}

			//feature情報をget
			//val[0]はtime
			int len = val.length;
			String feature = "";
			for(int i=1; i<len; i++){
				if(i == 1){
					feature += val[i];
				} else {
					feature += "," + val[i];
				}
			}
			if(element != null){
				outputMessage(feature + "," + element);
			}

		} else if (message == EnumCommand.BEGIN) {
			outputMessage(EnumCommand.BEGIN);
			try{
				InputStream inps;
				try {
					inps = getRuntimeContext().getFileStreamProvider().openInputStream(labelFilePath_);
					BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inps, RuntimeContext.DEFAULT_CHARSET));
					while(true){
						String line = bufferedReader.readLine();
						if (line == null) break;
						String[] columns = CSVUtil.parseCSVRecord(line);
						setLabelData(columns, labelDList_);
					}
					bufferedReader.close();
					inps.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}catch(RuntimeException ex) {
				CoreUtil.throwAsRuntimeException(ex);
			}

		} else {
			// その他のメッセージはそのまま出力
			outputMessage(message);
		}
	}

	public void setLabelFilePath(String labelFilePath){
		labelFilePath_ = labelFilePath;
	}
}
