/*   **********************************************************************  **
 **   Copyright notice                                                       **
 **                                                                          **
 **   (c) 2003-2006 RSSOwl Development Team                                  **
 **   http://www.rssowl.org/                                                 **
 **                                                                          **
 **   All rights reserved                                                    **
 **                                                                          **
 **   This program and the accompanying materials are made available under   **
 **   the terms of the Eclipse Public License 1.0 which accompanies this     **
 **   distribution, and is available at:                                     **
 **   http://www.rssowl.org/legal/epl-v10.html                               **
 **                                                                          **
 **   A copy is found in the file epl-v10.html and important notices to the  **
 **   license from the team is found in the textfile LICENSE.txt distributed **
 **   in this package.                                                       **
 **                                                                          **
 **   This copyright notice MUST APPEAR in all copies of the file!           **
 **                                                                          **
 **   Contributors:                                                          **
 **     RSSOwl - initial API and implementation (bpasero@rssowl.org)         **
 **                                                                          **
 **  **********************************************************************  */

package net.sourceforge.rssowl.util;

import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

/**
 * This class writes warning messages into a file
 * 
 * @author <a href="mailto:bpasero@rssowl.org">Benjamin Pasero </a>
 * @version 1.2.3
 */
public class LoggerImpl {

  /** Logger for RSSOwl */
  private static final Logger logger = Logger.getLogger("net.sourceforge.rssowl.controller");

  /** Maximum number of bytes before flushing logfile */
  private static final int MAX_LOG_SIZE = 100000;

  /** TRUE: Print errors into file FALSE: Print errors to System.err */
  private static boolean useFileHandler = true;

  /** Path used for the critical warning log file if needed */
  private String criticalErrorLogPath;

  /**
   * Creates a new instance of WiSimLogger
   */
  public LoggerImpl() {

    /** Log errors to file and dont use default handler from parent (System.err) */
    if (useFileHandler) {
      initFileHandler();

      /** Do not use parent handlers */
      logger.setUseParentHandlers(false);
    }

    /** Log to System.err */
    else {
      logger.setUseParentHandlers(true);
    }

    /** Log warnings */
    logger.setLevel(Level.WARNING);
  }

  /**
   * Log an info message
   * 
   * @param msg The method where the info did occur
   * @param t The Exception
   */
  public void info(String msg, Throwable t) {
    log(Level.INFO, "Method: " + msg + " Exception: " + t.getCause(), t);
  }

  /**
   * Log warning with no exception
   * 
   * @param msg The message
   */
  public void log(String msg) {
    log(Level.WARNING, msg, null);
  }

  /**
   * Log warning with a message
   * 
   * @param msg The method where the warning did occur
   * @param t The Exception
   */
  public void log(String msg, Throwable t) {
    log(Level.WARNING, msg, t);
  }

  /**
   * Log critical errors that cause RSSOwl to crash in a seperate, unique file.
   * This will avoid the flushing of the log file on next startup of RSSOwl to
   * review the warning later.
   * 
   * @param msg The message to log
   * @param t The Exception
   */
  public void logCritical(String msg, Throwable t) {
    Logger criticalLogger = Logger.getLogger("net.sourceforge.rssowl");
    criticalLogger.setUseParentHandlers(false);

    /** Use application dir as default */
    if (criticalErrorLogPath == null)
      criticalErrorLogPath = "log_critical_" + DateParser.dateToFileName(DateParser.formatDate(true)) + ".log";

    try {
      FileHandler criticalLogFileHandler = new FileHandler(criticalErrorLogPath);
      criticalLogFileHandler.setFormatter(new SimpleFormatter());
      criticalLogger.addHandler(criticalLogFileHandler);
    } catch (IOException e) {
      log("logCritical", e);
    }
    criticalLogger.log(Level.WARNING, "Method: " + msg + " Exception: " + t.getCause(), t);
  }

  /** Init the FileHandler to use with the logger */
  private void initFileHandler() {
    try {

      /** Log errors logs dir */
      FileHandler logFileHandler = new FileHandler(GlobalSettings.LOGS_DIR + GlobalSettings.PATH_SEPARATOR + "rssowllog.log", MAX_LOG_SIZE, 1, true);
      logFileHandler.setFormatter(new SimpleFormatter());
      logger.addHandler(logFileHandler);

      /** Init critical file handler */
      criticalErrorLogPath = GlobalSettings.LOGS_DIR + GlobalSettings.PATH_SEPARATOR + "log_critical_" + DateParser.dateToFileName(DateParser.formatDate(true)) + ".log";
    } catch (IOException e) {
      log("initFileHandler", e);
    }
  }

  /**
   * Perform a logging
   * 
   * @param level Level of the log
   * @param msg Message of the log
   * @param t Exception of the log
   */
  private void log(Level level, String msg, Throwable t) {
    if (msg == null)
      logger.log(level, "No Message", t);
    else if (t == null)
      logger.log(level, msg);
    else
      logger.log(level, "Method: " + msg + " Exception: " + t.getCause(), t);
  }
}