package net.oni2.aeinstaller.backend;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;

/**
 * @author Christian Illy
 */
public class LogPrintStream extends OutputStream {
	private static LogPrintStream instance = new LogPrintStream();

	private ByteArrayOutputStream baos = new ByteArrayOutputStream();
	private FileWriter fw = null;
	private PrintStream stdOut = null;

	private boolean logStdOut = true;

	private LogPrintStream() {
		stdOut = System.out;

		PrintStream ps = new PrintStream(this);
		System.setOut(ps);
		System.setErr(ps);
	}

	/**
	 * @return Logger instance
	 */
	public static LogPrintStream getInstance() {
		return instance;
	}

	/**
	 * Set the file to log to
	 * 
	 * @param logFile
	 *            Log file
	 * @throws IOException
	 *             Should not happen?!
	 */
	public void setFile(File logFile) throws IOException {
		if (fw != null)
			fw.close();
		fw = new FileWriter(logFile);
	}

	@Override
	public void write(int b) throws IOException {
		baos.write(b);
		if (logStdOut)
			stdOut.write(b);
		if (fw != null)
			fw.write(b);
	}

	/**
	 * @return Get the text that has been written to log up to now
	 */
	public String getLog() {
		return baos.toString();
	}

	@Override
	public void flush() throws IOException {
		stdOut.flush();
		baos.flush();
		if (fw != null)
			fw.flush();
	}

	@Override
	public void close() throws IOException {
		if (fw != null)
			fw.close();
		super.close();
	}
}
