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

import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;

import jp.hasc.hasctool.core.data.EnumCommand;
import jp.hasc.hasctool.core.runtime.RuntimeContext;

/**
 * 文字列系列を、Writerに1行づつ書き出します。
 * @author iwasaki
 */
public class LineWriterSink extends AbstractSink {
	private PrintWriter writer_;
	
	private String filePath_;
	
	@Override
	public void setup(RuntimeContext context) {
		super.setup(context);
		if (filePath_!=null && writer_==null) {
			OutputStream outs = getRuntimeContext().getFileStreamProvider().openOutputStream(filePath_);
			setWriter(new OutputStreamWriter(outs, RuntimeContext.DEFAULT_CHARSET));
		}
	}

	@Override
	public void processMessage(Object message) throws InterruptedException {
		if (message instanceof String) {
			writer_.println((String)message);
		}else if (message==EnumCommand.BEGIN) {
			// NOP
		}else if (message==EnumCommand.END) {
			writer_.close();
			writer_=null;
		}else{
			// Umm...
			writer_.println(message.toString());
		}
	}

	public void setWriter(Writer writer) {
		writer_ = new PrintWriter(writer);
	}
	
	public void setFilePath(String filePath) {
		filePath_=filePath;
	}
}
