package yi.util.log;

import yi.util.config.*;

/**
 * Log handler
 */
public abstract class LogHandler implements Configurable{

  /**
   * The system log handler type.   Default to standard which use System.out
   */
  public static String LOG_HANDLER_TYPE = "yi.util.log.LH_Standard";

  /**
   * LogHandler Singleton
   */
  private static LogHandler m_logHandler = null;

  public static LogHandler getSingleton() {
    if (m_logHandler != null) return m_logHandler;
    else {
      // get the log handler type from Configuration
      LOG_HANDLER_TYPE = Configuration.getStringParameter(
        "LOG_HANDLER_TYPE", LOG_HANDLER_TYPE);
      try {
        Class c = Class.forName(LOG_HANDLER_TYPE);
        m_logHandler = (LogHandler)c.newInstance();
      }
      catch (ClassNotFoundException e) {
        System.err.println("Can't find the log handler specified");
        e.printStackTrace();
        m_logHandler = new LH_Standard();
      }
      catch (Exception e) {
        System.err.println("Not a valid class for log handler");
        e.printStackTrace();
        m_logHandler = new LH_Standard();
      }
    }
    return m_logHandler;
  }

  abstract public void writeLog(Object obj, int verbose_level, int log_level, String msg);

  /**
   * Write a message to log handler
   * @param obj the object related to the message
   * @param verbose_level predefined verbose level.  If verbose_level = 0, then
   *                      only level 0 messages will be written.  If
   *                      verbose_level = 3, then only level 0,1,2,3 messages
   *                      (log_level <= verbose_level) will be written.
   * @param log_level the importantance of the message.  The lower, the more
   *                  important
   * @param msg the message
   */
  public static void log(Object obj, int verbose_level, int log_level, String msg) {
    LogHandler h = getSingleton();
    h.writeLog(obj, verbose_level, log_level, msg);
  }

  public String[] getParameterNames() {
    return new String[] {
      "LOG_HANDLER_TYPE"
    };
  }
}