package com.starbucks.eom.tools.log4j;

import java.util.HashMap;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggerFactory;

/**
 * Manages the creation/retrieval of Logger Objects for all interfaces for a specific class
 * given the interfaceName.  To be used when one class services multiple interfaces.
 */
public class InterfaceLoggerFactory implements LoggerFactory {
	private static final Logger log = Logger.getLogger(InterfaceLoggerFactory.class);
	String className;
	HashMap categoriesByInterface = new HashMap(14);

	/**
	 * Recommended convenience constructor which defaults the class name prefix used by this factory to the
	 * fully qualified class name passed in.
	 */
	public InterfaceLoggerFactory(Class clazz) {
		this(clazz.getName());
	}

	/**
	 * Creates a Logger factory for the given class name.  The class name is used the prefix for
	 * a category name.
	 */
	public InterfaceLoggerFactory(String clazzName) {
		className = clazzName;
	}

    /**
     * Retrieves the specific interface category for the class used to construct
     * this factory.  If the given iterface has not be used a new instance of the Logger
     * is created and stored for later use.
     *
     * @input interfaceName  name of the interface
     *
     * @return category used for loggin the messages specific to the given interface.
     *
     */
   	public Logger makeNewLoggerInstance(String interfaceName) {
		String loggerName = getLoggerName(interfaceName);
   		Logger loggerInstance = (Logger) categoriesByInterface.get(loggerName);
   		if (loggerInstance == null) {
   			loggerInstance = Logger.getLogger(loggerName);
   			categoriesByInterface.put(loggerName, loggerInstance);
   			log.debug("caching new logger:" + loggerName);
   		} else {
   			log.debug("returning cached logger");
   		}
   		return loggerInstance;
    }

    private String getLoggerName(String interfaceName) {
    	return className + "." + interfaceName;
    }
}
