package Tools;

import java.util.*;
import java.io.*;

/**
 * Tools for logging messages to the console (or another OutputStream).
 * Messages can belong to different categories (<code>level</code>s),
 * analogous to syslog.
 */
public class Log {

	public void log(String message) {
		logc("default", message+"\n");
	}

	public void log(String level, String message) {
		logc(level, message+"\n");
	}

	public void logc(String level, String message) {
		if (logHash.containsKey(level)) {
			try {
				writer.write(prefix+message);
				writer.flush();
			} catch (IOException ex) { }
		}
	}

	// a test you can use before printing a message
	public boolean logt(String level) {
		return logHash.containsKey(level);
	}

	// a stream you can print to; don't forget to flush!
	public OutputStream logs(String level) {
		if (logHash.containsKey(level)) {
			return os;
		} else {
			return nullStream;
		}
	}

	public PrintWriter logw(String level) {
		if (logHash.containsKey(level)) {
			return printWriter;
		} else {
			return nullWriter;
		}
	}

	public Log addLevel(String level) {
		logHash.put(level, this);
		return this;
	}

	public Log setPrefix(String prefix) {
		this.prefix = prefix;
		return this;
	}

	public Log() {
		this(System.err);
	}

	public Log(OutputStream os) {
		this(os, "");
	}

	public Log(String prefix) {
		this(System.err, prefix);
	}

	public Log(OutputStream os, String prefix) {
		this.os = os;
		this.writer = new OutputStreamWriter(os);
		this.printWriter = new PrintWriter(writer);
		this.prefix = prefix;
		logHash = new Hashtable(2);
	}


	String				prefix;
	OutputStream		os;
	OutputStreamWriter	writer;
	PrintWriter			printWriter;
	Hashtable logHash;

	static OutputStream nullStream = new OutputStream() {
			public void write(int b) throws IOException {}
			public void write(byte[] b) throws IOException {}
			public void write(byte[] b, int off, int len) throws IOException {}
		};
	static PrintWriter nullWriter =
		new PrintWriter(new OutputStreamWriter(nullStream));
}
