package jp.hasc.hasctool.core.runtime.sink;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
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.runtime.RuntimeContext;

/**
 * 文字列系列を、Writerに1行づつ書き出します。
 * 出力ファイル名は入力ファイル名毎に変わります
 * @author hiro
 */
public class ExtensionWriterSink extends AbstractSink {
	
	private ArrayList<String> dataList_;
	private String filePath_;
	private String fileName_;
	private String feature_;
	private String folderPath_;

	public void setInputFilePath(String inputPath){
		String[] fnVal = inputPath.split("/");
		fileName_ = fnVal[fnVal.length-1];
	}
	
	public void setOutputFolder(String folderPath){
		folderPath_ = folderPath;
	}
	
	public void setFeature(String feature){
		feature_ = feature;
	}

	@Override
	public void processMessage(Object message) throws InterruptedException {
		if (message instanceof String) {
			dataList_.add((String)message);
		
		}else if (message==EnumCommand.BEGIN) {
			dataList_ = new ArrayList<String>();
			
		}else if (message==EnumCommand.END) {
			filePath_ = folderPath_ + "/" + feature_ + "_" +fileName_;
			if (filePath_ != null) {
				try {
					OutputStream outs;
					outs = new FileOutputStream(filePath_);
					PrintWriter writer = new PrintWriter(
							new OutputStreamWriter(outs,
									RuntimeContext.DEFAULT_CHARSET));
					for(int i=0; i<dataList_.size(); i++){
						writer.println(dataList_.get(i));
					}
					writer.close();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
			}
		}else{
			// Umm...
			dataList_.add(message.toString());
		}
	}
}
