/*
 * This file is part of Nuts Framework.
 * Copyright(C) 2009-2012 Nuts Develop Team.
 *
 * Nuts Framework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License any later version.
 * 
 * Nuts Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Nuts Framework. If not, see <http://www.gnu.org/licenses/>.
 */
package nuts.core.log;

import nuts.core.lang.Classes;
import nuts.core.lang.Systems;
import nuts.core.log.impl.ConsoleLogAdapter;
import nuts.core.log.impl.NopLog;


public final class Logs {
	private static LogAdapter adapter;

	static {
		init();
		try {
			get().info("Nuts is licensed under the GNU General Public License 3. " 
				+ "Report bugs: https://code.google.com/p/nutsfw/issues");
		}
		catch (Throwable e) {
			// just pass!!
		}
	}

	/**
	 * Get a Log by Class
	 * 
	 * @param clazz your class
	 * @return Log
	 */
	public static Log getLog(Class<?> clazz) {
		return getLog(clazz.getName());
	}

	/**
	 * Get a Log by name
	 * 
	 * @param className the name of Log
	 * @return Log
	 */
	public static Log getLog(String className) {
		return adapter.getLogger(className);
	}

	/**
	 * get a log by caller's class name
	 */
	public static Log get() {
		StackTraceElement[] sts = Thread.currentThread().getStackTrace();
		if (Systems.IS_OS_ANDROID) {
			for (int i = 0; i < sts.length; i++) {
				if (sts[i].getClassName().equals(Logs.class.getName())) {
					return adapter.getLogger(sts[i + 1].getClassName());
				}
			}
		}
		return adapter.getLogger(sts[2].getClassName());
	}

	private static void init() {
		String[] adapters = new String[] {
				ConsoleLogAdapter.class.getPackage().getName() + ".Log4jLogAdapter"
		};

		for (String a : adapters) {
			try {
				adapter = (LogAdapter)Classes.newInstance(a);
				break;
			}
			catch (Throwable e) {
				//pass
			}
		}

		if (adapter == null) {
			adapter = new ConsoleLogAdapter();
		}
	}

	/**
	 * set the log adapter, null to disable log
	 * 
	 * @param adapter customer LogAdapter
	 */
	public static void setAdapter(LogAdapter adapter) {
		if (adapter == null) {
			adapter = NopLog.NOP;
		}
		Logs.adapter = adapter;
	}
}
