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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import jp.hasc.hasctool.core.data.SignalMessage;
import jp.hasc.hasctool.core.runtime.RuntimeContext;
import jp.hasc.hasctool.core.util.CoreUtil;

/**
 * Readerから1行づつ読み取り、文字列系列として出力します。
 * @author iwasaki
 */
public class LineReaderSource extends AbstractSource {
	private String filePath_;
	private BufferedReader bufferedReader_;
	
	public void setReader(Reader reader) {
		bufferedReader_=new BufferedReader(reader);
	}
	
	@Override
	public void setup(RuntimeContext context) {
		super.setup(context);
		if (filePath_!=null && bufferedReader_==null) {
			try{
				InputStream inps = getRuntimeContext().getFileStreamProvider().openInputStream(filePath_);
				setReader(new InputStreamReader(inps, RuntimeContext.DEFAULT_CHARSET));
			}catch(RuntimeException ex) {
				CoreUtil.throwAsRuntimeException(ex);
			}
		}
	}

	@Override
	protected void run() throws InterruptedException {
		outputMessage(SignalMessage.BEGIN);
		
		if (bufferedReader_!=null) try {
			while (!isShutdown()) {
				String line = bufferedReader_.readLine();
				if (line == null) break;
				outputMessage(line);
			}
			bufferedReader_.close();
		} catch (IOException ex) {
			CoreUtil.throwAsRuntimeException(ex);
		}
		outputMessage(SignalMessage.END);
	}
	
	public void setFilePath(String filePath) {
		filePath_=filePath;
	}
}
