package jp.hasc.hasctool.core.runtime.filter.evaluation;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;

import jp.hasc.hasctool.core.data.EnumCommand;
import jp.hasc.hasctool.core.data.VectorSignalMessage;
import jp.hasc.hasctool.core.runtime.RuntimeContext;
import jp.hasc.hasctool.core.runtime.sink.AbstractSink;
import jp.hasc.hasctool.core.util.CoreUtil;


/**
 * ラベル付で書き込みを行うフィルタです
 * @author hiro
 */
public class WriterAppendWithLabelFilter extends AbstractSink{

	String activity_;
	String fileSystemPath_;
	ArrayList<String> futureList_;
	
	public WriterAppendWithLabelFilter() {
		futureList_ = new ArrayList<String>();
	}

	public void setFileSystemPath(String fileSystemPath) {
		fileSystemPath_=fileSystemPath;
	}

	public void setActivity(String activity) {
		activity_=activity;
	}


	private void setData(String line) {
		futureList_.add(line);
	}


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


	@Override
	public void processMessage(Object message) throws InterruptedException {
		if (message instanceof VectorSignalMessage) {
			// VectorSignalMessageの場合
			VectorSignalMessage vsig = (VectorSignalMessage)message;
			// 新しいベクトルの値を計算
			double[] newValue=new double[vsig.getVectorSize()];
			String line = activity_;
			for(int i=0; i<newValue.length; ++i){
				line += "," + vsig.getVectorElement(i);
			}
			setData(line);


		}else if (message==EnumCommand.BEGIN) {
			try{
				InputStream inps;
				try {
					inps = new FileInputStream(fileSystemPath_);
					BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inps, RuntimeContext.DEFAULT_CHARSET));
					while(true){
						String line = bufferedReader.readLine();
						if (line == null) break;
						setData(line);
					}
					bufferedReader.close();
					inps.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}catch(RuntimeException ex) {
				CoreUtil.throwAsRuntimeException(ex);
			}


		} else if (message == EnumCommand.END) {
			if (fileSystemPath_ != null) {
				try {
					OutputStream outs;
					outs = new FileOutputStream(fileSystemPath_);
					PrintWriter writer = new PrintWriter(
							new OutputStreamWriter(outs,
									RuntimeContext.DEFAULT_CHARSET));

					for(int i=0; i<futureList_.size(); i++){
						String row = futureList_.get(i);
						writer.print(row);
						writer.println();
					}
					writer.close();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
			}
		} else {
		}
	}
}
