package org.slf4j;

import sun.misc.Service;
import org.slf4j.impl.Util;
import java.util.Iterator;

/**
 * This class is a simple wrapper over Sun's Service provider
 * factory. It provides a standard mechanism for loading plugins
 * in a simple way.
 */
public abstract class LoggerFactory {

  private static final ILoggerFactory factory;

  // Initialize the real ILoggerFactory
  static {

    ILoggerFactory f = null;
    try {

      // Use the current context ClassLoader to enumerate all the resources
      // that define ILoggerFactory services.
      for(Iterator i = Service.providers(ILoggerFactory.class); i.hasNext(); ) {
        Object o = i.next();
        if(f == null)
          f = (ILoggerFactory)o;
        else
          Util.reportWarning("More than once service provider was defined");
      }

    } catch(Throwable t) {
      Util.reportFailure("Failed to load service providers", t);
    }

    factory = f;
    if(f == null) {
      // TODO: Should there be a simple fall back on a System.out logger?
      // TODO: Perhaps the simple loggers is included with SLF4J-API and 
      // TODO: Is selected always, unless another implementation is provided
    }

  }

  public static Logger getLogger(Class name) {
    return getLogger(name.getName());
  }

  public static Logger getLogger(String name) {
    if(factory != null)
      return factory.getLogger(name);
    // TODO: Not a problem if the above suggestion is taken
    throw new IllegalStateException("No " + ILoggerFactory.class + " implementation was provided!");
  }

}
