/*
 * The contents of this file are subject to the Mozilla Public License Version 1.1
 * (the "License"); you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
 * 
 * Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
 * WARRANTY OF ANY KIND, either express or implied. See the License for the specific
 * language governing rights and limitations under the License.
 * 
 * The Original Code is the Venice Web Communities System.
 * 
 * The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
 * for Silverwrist Design Studios.  Portions created by Eric J. Bowersox are
 * Copyright (C) 2002 Eric J. Bowersox/Silverwrist Design Studios.  All Rights Reserved.
 * 
 * Contributor(s): 
 */
package com.silverwrist.dynamo.security;

import java.util.*;
import org.w3c.dom.*;
import com.silverwrist.util.xml.*;
import com.silverwrist.dynamo.db.NamespaceCache;
import com.silverwrist.dynamo.db.UserProxyManagement;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.util.*;

public class SystemAuditManager
    implements NamedObject, ComponentInitialize, ComponentShutdown, ServiceProvider, AuditRecordFactory,
               AuditRecordRetrieval
{
  /*--------------------------------------------------------------------------------
   * Attributes
   *--------------------------------------------------------------------------------
   */

  private String m_name;                                    // object name
  private DBConnectionPool m_pool;                          // database connection pool
  private NamespaceCache m_ns_cache;                        // namespace cache object
  private UserProxyManagement m_proxy;                      // proxy management for users
  private AuditWriteOps m_write_ops;                        // audit write operations
  private AuditReadOps m_read_ops;                          // audit read operations
  private ComponentShutdown m_shut_script;                  // shutdown for scripting object
  private ComponentShutdown m_shut_1;                       // shutdown for hooks
  private ComponentShutdown m_shut_2;                       // shutdown for hooks
  private ComponentShutdown m_shut_3;                       // shutdown for hooks

  /*--------------------------------------------------------------------------------
   * Constructor
   *--------------------------------------------------------------------------------
   */

  public SystemAuditManager()
  { // do nothing
  } // end constructor

  /*--------------------------------------------------------------------------------
   * Implementations from interface NamedObject
   *--------------------------------------------------------------------------------
   */

  public String getName()
  {
    return m_name;

  } // end getName

  /*--------------------------------------------------------------------------------
   * Implementations from interface ComponentInitialize
   *--------------------------------------------------------------------------------
   */

  public void initialize(Element config_root, ServiceProvider services) throws ConfigException
  {
    String conn_name = null;
    String nscache_name = null;
    String proxy_name = null;
    XMLLoader loader = XMLLoader.get();
    try
    { // verify the right node name
      loader.verifyNodeName(config_root,"object");

      // get the object's name
      m_name = loader.getAttribute(config_root,"name");

      // get the database configuration connection
      Element elt = loader.getSubElement(config_root,"database");
      conn_name = loader.getAttribute(elt,"connection");
      nscache_name = loader.getAttribute(elt,"namespaces");
      proxy_name = loader.getAttribute(elt,"userproxy");

    } // end try
    catch (XMLLoadException e)
    { // error loading XML config data
      throw new ConfigException(e);

    } // end catch

    // Get the database connection pool and the namespace cache.
    m_pool = GetObjectUtils.getDatabaseConnection(services,conn_name);
    m_ns_cache =
        (NamespaceCache)(GetObjectUtils.getDynamoComponent(services,NamespaceCache.class,nscache_name));
    m_proxy =
        (UserProxyManagement)(GetObjectUtils.getDynamoComponent(services,UserProxyManagement.class,
								proxy_name));

    // Create the operations objects.
    m_write_ops = AuditWriteOps.get(m_pool);
    m_read_ops = AuditReadOps.get(m_pool);

    // Add an object to the script engine to make writing audit records easier.
    ScriptEngineConfig sconf = (ScriptEngineConfig)(services.queryService(ScriptEngineConfig.class));
    m_shut_script = sconf.addDeclaredObject("audit",new LibraryAudit(this),LibraryAudit.class);

    // Hook the various services to allow us to easily write audit records.
    SingletonServiceProvider ssp = new SingletonServiceProvider("SystemAuditManager",AuditRecordFactory.class,
								(AuditRecordFactory)this);
    HookServiceProviders hooker = (HookServiceProviders)(services.queryService(HookServiceProviders.class));
    m_shut_1 = hooker.hookInitServiceProvider(ssp);
    m_shut_2 = hooker.hookRuntimeServiceProvider(ssp);
    m_shut_3 = hooker.hookOutputServiceProvider(ssp);

  } // end initialize

  /*--------------------------------------------------------------------------------
   * Implementations from interface ComponentShutdown
   *--------------------------------------------------------------------------------
   */

  public void shutdown()
  {
    m_shut_3.shutdown();
    m_shut_3 = null;
    m_shut_2.shutdown();
    m_shut_2 = null;
    m_shut_1.shutdown();
    m_shut_1 = null;
    m_shut_script.shutdown();
    m_shut_script = null;
    m_read_ops = null;
    m_write_ops = null;
    m_proxy = null;
    m_ns_cache = null;
    m_pool = null;

  } // end shutdown

  /*--------------------------------------------------------------------------------
   * Implementations from interface ServiceProvider
   *--------------------------------------------------------------------------------
   */

  /**
   * Queries this object for a specified service.
   *
   * @param klass The class of the object that should be returned as a service.
   * @return A service object.  The service object is guaranteed to be of the class
   *         specified by <CODE>klass</CODE>; that is, if <CODE>queryService(klass)</CODE>
   *         yields some object <CODE>x</CODE>, then the expression <CODE>klass.isInstance(x)</CODE>
   *         is true.
   * @exception com.silverwrist.dynamo.except.NoSuchServiceException If no service is available in
   *            the specified class.
   */
  public Object queryService(Class klass)
  {
    if (klass==AuditRecordFactory.class)
      return (AuditRecordFactory)this;
    if (klass==AuditRecordRetrieval.class)
      return (AuditRecordRetrieval)this;
    throw new NoSuchServiceException("SystemAuditManager",klass);

  } // end queryService

  /**
   * Queries this object for a specified service.
   *
   * @param klass The class of the object that should be returned as a service.
   * @param serviceid ID for the service to be requested, to further discriminate between requests.
   * @return A service object.  The service object is guaranteed to be of the class
   *         specified by <CODE>klass</CODE>; that is, if <CODE>queryService(klass)</CODE>
   *         yields some object <CODE>x</CODE>, then the expression <CODE>klass.isInstance(x)</CODE>
   *         is true.
   * @exception com.silverwrist.dynamo.except.NoSuchServiceException If no service is available in
   *            the specified class.
   */
  public Object queryService(Class klass, String serviceid)
  {
    if (klass==AuditRecordFactory.class)
      return (AuditRecordFactory)this;
    if (klass==AuditRecordRetrieval.class)
      return (AuditRecordRetrieval)this;
    throw new NoSuchServiceException("SystemAuditManager",klass,serviceid);

  } // end queryService

  /*--------------------------------------------------------------------------------
   * Implementations from interface AuditRecordFactory
   *--------------------------------------------------------------------------------
   */

  public AuditRecordCompose createAuditRecord(Request r, DynamoUser user, String namespace, String name)
  {
    return new WriteAuditRecord(m_write_ops,m_ns_cache,r.getSourceAddress(),user,0,namespace,name);

  } // end createAuditRecord

  public AuditRecordCompose createAuditRecord(Request r, DynamoUser user, int subid, String namespace,
					      String name)
  {
    return new WriteAuditRecord(m_write_ops,m_ns_cache,r.getSourceAddress(),user,subid,namespace,name);

  } // end createAuditRecord

  public AuditRecordCompose createSystemAuditRecord(String namespace, String name)
  {
    return new WriteAuditRecord(m_write_ops,m_ns_cache,"127.0.0.1",null,0,namespace,name);

  } // end createSystemAuditRecord

  /*--------------------------------------------------------------------------------
   * Implementations from interface AuditRecordRetrieval
   *--------------------------------------------------------------------------------
   */

  public AuditRecordSet getAuditRecords(java.util.Date start_date, java.util.Date end_date)
      throws DatabaseException
  {
    List l;
    if (start_date==null)
    { // select the correct function to call
      if (end_date==null)
	l = m_read_ops.getAllAuditIDs();
      else
	l = m_read_ops.getAuditIDsBefore(end_date);

    } // end if
    else if (end_date==null)
      l = m_read_ops.getAuditIDsAfter(start_date);
    else
      l = m_read_ops.getAuditIDs(start_date,end_date);
    return new ReadAuditRecordSet(m_read_ops,m_ns_cache,m_proxy,l);

  } // end getAuditRecords

  public AuditRecordSet getAuditRecords(java.util.Date start_date, java.util.Date end_date, int subid)
      throws DatabaseException
  {
    List l;
    if (start_date==null)
    { // select the correct function to call
      if (end_date==null)
	l = m_read_ops.getAllAuditIDs(subid);
      else
	l = m_read_ops.getAuditIDsBefore(end_date,subid);

    } // end if
    else if (end_date==null)
      l = m_read_ops.getAuditIDsAfter(start_date,subid);
    else
      l = m_read_ops.getAuditIDs(start_date,end_date,subid);
    return new ReadAuditRecordSet(m_read_ops,m_ns_cache,m_proxy,l);

  } // end getAuditRecords

} // end class SystemAuditManager
