package jp.agentec.sinaburocast.common.proc;

import java.io.BufferedReader;
import java.io.IOException;

import jp.agentec.sinaburocast.common.SinaburoConstant.Formats;

import org.apache.commons.logging.Log;

/**
 * 標準出力、標準出力読み出し専用スレッド・クラス
 * 
 * @author tsukada
 *
 */
public class StreamPumper extends Thread {
	private String type;
	private BufferedReader br;
	private StringBuffer sb;
	private Log logger;
	private String logLevel;
	private boolean endOfStream = false;
	private boolean finish = false;
	private static final int SLEEP_TIME = 5;

	public StreamPumper(String type, BufferedReader br, StringBuffer sb, Log logger, String logLevel) {
		this.br = br;
		this.type = type;
		this.sb = sb;
		this.logger = logger;
		this.logLevel = logLevel;
	}

	/**
	 * ストリーム出力をログ出力する
	 * @throws IOException
	 */
	public void pumpStream() throws IOException {
		if (!endOfStream) {
			String line = br.readLine();

			if (line == null) {
				endOfStream = true;
			} else {
				if (logLevel == null) {
				}
				else if (logLevel.equals("debug")) {
					if (logger.isDebugEnabled()){
						logger.debug(type + ": " + line);
					}
				}
				else if (logLevel.equals("info")) {
					if (logger.isInfoEnabled()){
						logger.info(type + ": " + line);
					}
				}
				else if (logLevel.equals("warn")) {
					logger.warn(type + ": " + line);
				}
				else if (logLevel.equals("error")) {
					logger.error(type + ": " + line);
				}

				if (sb != null) {
					sb.append(line+ Formats.RETURN);
				}
			}
		}
	}

	/**
	 * 終了フラグを立てる
	 */
	public void finish() {
		finish = true;
	}

	public void run() {
		try {
			try {
				while (!endOfStream && !finish) {
					pumpStream();
					sleep(SLEEP_TIME);
				}
			} catch (InterruptedException e) {
				if (logger != null) {
					logger.warn(e.getMessage());
				}
			}
			br.close();
		} catch (IOException e) {
			if (logger != null) {
				logger.warn(e.getMessage());
			}
		}
	}
}