package hiro.yoshioka.util.logging;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Handler;
import java.util.logging.Logger;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.impl.Jdk14Logger;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.graphics.Color;

public class LogUtil {
	private static Log log = LogFactory.getLog(LogUtil.class);
	private static AbsMyLoggingHandler myLoggingHandler;
	public static String[] A_LEVELS;
	public static String[] LEVELS;
	private static final boolean isJDK14Logger;
	static {
		if (log instanceof Jdk14Logger) {
			isJDK14Logger = true;
			A_LEVELS = new String[] { "SEVERE", "WARNING", "INFO", "CONFIG",
					"FINE", "FINER", "FINEST" };
			LEVELS = new String[] { "OFF", "SEVERE", "WARNING", "INFO",
					"CONFIG", "FINE", "FINER", "FINEST", "ALL" };
		} else {
			isJDK14Logger = false;
			A_LEVELS = new String[] { "FATAL", "ERROR", "WARN", "INFO",
					"DEBUG", "TRACE" };
			LEVELS = new String[] { "OFF", "FATAL", "ERROR", "WARN", "INFO",
					"DEBUG", "TRACE", "ALL" };
		}
	}

	private static LogUtil single = new LogUtil();

	private static Map<String, Color> fColorMap = new HashMap<String, Color>();

	public static void main(String[] args) {
		// LogUtil.
	}

	private LogUtil() {
		System.out.println("//=====================================");
		if (isJDK14Logger) {
			System.out.println("// LOGGER IS JDK14 LOGGER");
			myLoggingHandler = new JDK14MyLoggingHandler();

		} else {
			System.out.println("// LOGGER IS LOG4J LOGGER");
			myLoggingHandler = new Log4JLoggingHandler();

		}
		System.out.println("//=====================================");
	}

	public static void setLevel(String level) {
		myLoggingHandler.setLevel(level);
	}

	public static String getLevel() {
		return myLoggingHandler.getLevel();
	}

	public static void setColorLevel(String levelName, Color fg, Color bg) {
		myLoggingHandler.getfColorMap().put(levelName + "_F", fg);
		myLoggingHandler.getfColorMap().put(levelName + "_B", bg);
	}

	public static void connect(StyledText text) {
		myLoggingHandler.connect(text);
	}

	public static void dump(Logger tlogger) {
		for (int i = 0; tlogger != null && tlogger.getName().length() > 0; i++) {
			System.out.println(tlogger);
			System.out.println(tlogger.getName());
			Handler[] handlers = tlogger.getHandlers();
			if (handlers != null) {
				for (int j = 0; j < handlers.length; j++) {
					System.out.println(" " + handlers[j] + "/"
							+ handlers[j].getLevel());
				}
			}
			tlogger = tlogger.getParent();
		}
	}

}