/*
 * LogUtil.java  $Revision: 1.3 $  $Date: 2007/10/03 04:39:39 $
 *
 * Copyright (C) 2007 Meldcraft Corporation
 *
 * This file is part of Scaffold.
 * 
 * Scaffold is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Scaffold 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 Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with Scaffold.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.meldcraft.util.logging;

import java.io.IOException;
import java.util.HashMap;
import java.util.logging.ConsoleHandler;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @version $Revision: 1.3 $ $Date: 2007/10/03 04:39:39 $
 * @author Rob Richards
 */
public class LogUtil
{
// Static variables
    private static final HashMap    sLoggers = new HashMap();
    private static final Object     sDefaultLoggerKey = new Object();

// Member variables
// Constructors and initialization
    // prevent instantiation
    private LogUtil()
    {
    }

// Interface implemenations
// Public methods
    /**
     * Sets the default logger.  The logger can be set only once; subsequent
     * calls throw an Error.
     */
    public static void setDefaultLogger(Logger logger)
    {
        synchronized(sLoggers)
        {
            if (sLoggers.get(sDefaultLoggerKey) != null)
            {
                throw new Error("Logger already set.");
            }
            else if (logger != null)
            {
                sLoggers.put(sDefaultLoggerKey, logger);
            }
        }
    }

    /**
     * Returns the default logger, if one has be set; otherwise, returns null.
     */
    public static Logger getDefaultLogger()
    {
        Logger ret;

        synchronized(sLoggers)
        {
            ret = (Logger)sLoggers.get(sDefaultLoggerKey);
        }

        return ret;
    }

    /**
     * Returns the default logger, if one has been set.  Otherwise, returns
     * a unique logger for the object package (in the manner of
     * java.util.logging.Logger.getLogger(String)).
     */
    public static Logger getLogger(Object object)
    {
        Logger ret = getDefaultLogger();

        if (ret == null)
        {
            ret = getLogger(object, null, 0, 0, null);
        }

        return ret;
    }

    /**
     * Set the logger for all objects in the object package.
     */
    public static void setLogger(Logger logger, Object object)
    {
        synchronized(sLoggers)
        {
            sLoggers.put(getPackageName(object), logger);
        }
    }

    /**
     * Returns a unique logger for the object package (in the manner of
     * java.util.logging.Logger.getLogger(String)).
     */
    public static Logger getLogger(Object object, String filepath,
                                   int sizeLimit, int fileCount,
                                   Level level)
    {
        Logger logger;
        String pkgname = getPackageName(object);

        synchronized(sLoggers)
        {
            logger = (Logger)sLoggers.get(pkgname);
            if (logger == null)
            {
                logger = Logger.getLogger(pkgname);
                sLoggers.put(pkgname, logger);
                setHandlers(logger, filepath, sizeLimit, fileCount,
                            level, false);
            }
        }

        return logger;
    }

    /**
     * Adds new handlers to the logger, and then removes the old handlers.
     */
    public static void setHandlers(Logger logger, String filepath,
                                   int sizeLimit, int fileCount,
                                   Level level, boolean logToConsole)
    {
        Handler[] handlers = logger.getHandlers();

        addHandlers(logger, filepath, sizeLimit, fileCount, level,
                    logToConsole);

        if (handlers != null)
        {
            for (int i=0 ; i < handlers.length ; i++)
            {
                logger.removeHandler(handlers[i]);
            }
        }
    }

    /**
     * Adds handlers to the logger.
     */
    public static void addHandlers(Logger logger, String filepath,
                                   int sizeLimit, int fileCount,
                                   Level level, boolean logToConsole)
    {
        if (sizeLimit == 0)
        {
            // limited size - approximately zero
            sizeLimit = 1;
        }
        else if (sizeLimit < 0)
        {
            // unlimited size
            sizeLimit = 0;
        }

        if (fileCount < 1)
        {
            fileCount = 1;
        }

        if (level == null)
        {
            level = Level.INFO;
        }

        boolean useConsole = ((filepath == null) || (filepath.length() == 0));
        try
        {
            if (!useConsole)
            {
                FileHandler handler = new FileHandler(filepath+".log", sizeLimit, fileCount, true);
                handler.setFormatter(new DateTimeFormatter());
                handler.setLevel(level);

                logger.addHandler(handler);
                logger.setUseParentHandlers(false);
            }
        }
        catch (IOException e)
        {
            // ignored - use default logging
            useConsole = true;
            System.err.println("Error creating log file handler: "+e.getClass().getName()+": "+e.getMessage());
        }

        if (useConsole || logToConsole)
        {
            try
            {
                ConsoleHandler handler = new ConsoleHandler();
                handler.setFormatter(new DateTimeFormatter());
                handler.setLevel(level);

                logger.addHandler(handler);
                logger.setUseParentHandlers(false);
            }
            catch (Exception ce)
            {
                System.err.println("Error creating console handler: "+ce.getClass().getName()+": "+ce.getMessage());
            }
        }

        logger.setLevel(level);
    }

// Protected methods
// Private methods
    private static String getPackageName(Object object)
    {
        String pkgname;
        if (object instanceof String)
        {
            pkgname = (String)object;
        }
        else
        {
            Class clazz = object.getClass();
            if (object instanceof Class)
            {
                clazz = (Class)object;
            }
            pkgname = clazz.getName();
        }

        int idx = pkgname.lastIndexOf('.');
        if (idx > 0)
        {
            pkgname = pkgname.substring(0, idx);
        }

        return pkgname;
    }

// Inner classes
}
