/*
 * 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.app;

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

public class ConnectionManager implements NamedObject, ComponentInitialize, ComponentShutdown
{
  /*--------------------------------------------------------------------------------
   * Internal class implementing the initialization service hook
   *--------------------------------------------------------------------------------
   */

  private class InitService implements ServiceProvider, ConnectionFrontEnd, ConnectionBackEnd
  {
    /*====================================================================
     * Constructor
     *====================================================================
     */

    InitService()
    { // do nothing
    } // end constructor

    /*====================================================================
     * 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==ConnectionFrontEnd.class)
	return (ConnectionFrontEnd)this;
      if (klass==ConnectionBackEnd.class)
	return (ConnectionBackEnd)this;
      throw new NoSuchServiceException("ConnectionManager.InitService",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==ConnectionFrontEnd.class)
	return (ConnectionFrontEnd)this;
      if (klass==ConnectionBackEnd.class)
	return (ConnectionBackEnd)this;
      throw new NoSuchServiceException("ConnectionManager.InitService",klass,serviceid);

    } // end queryService

    /*====================================================================
     * Implementations from interface ConnectionFrontEnd
     *====================================================================
     */

    public Object getInterface(String connection_point, Class expected_class) throws ConfigException
    {
      return getConnectionPoint(connection_point).getInterface(expected_class);

    } // end getInterface

    /*====================================================================
     * Implementations from interface ConnectionBackEnd
     *====================================================================
     */

    public void connectObject(String connection_point, Object object) throws ConfigException
    {
      getConnectionPoint(connection_point).connectObject(object);

    } // end connectObject

  } // end class InitService

  /*--------------------------------------------------------------------------------
   * Attributes
   *--------------------------------------------------------------------------------
   */

  private String m_name;
  private Hashtable m_connection_points = new Hashtable();
  private ComponentShutdown m_shutdown_hook;

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

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

  /*--------------------------------------------------------------------------------
   * Internal operations
   *--------------------------------------------------------------------------------
   */

  private final ConnectionPoint getConnectionPoint(String name) throws ConfigException
  {
    ConnectionPoint rc = (ConnectionPoint)(m_connection_points.get(name));
    if (rc!=null)
      return rc;
    ConfigException ce = new ConfigException(ConnectionPoint.class,"ConnectionMessages","cpoint.notFound");
    ce.setParameter(0,name);
    throw ce;

  } // end getConnectionPoint

  /*--------------------------------------------------------------------------------
   * 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
  {
    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 connection points list and try to load them
      List l = loader.getMatchingSubElements(config_root,"connection-point");
      Iterator it = l.iterator();
      while (it.hasNext())
      { // create the connection points
	Element elt = (Element)(it.next());
	ConnectionPoint cpoint = new ConnectionPoint(elt);
	m_connection_points.put(cpoint.getName(),cpoint);

      } // end while

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

    } // end catch

    // Hook the init service provider to provide our services.
    HookServiceProviders hooker = (HookServiceProviders)(services.queryService(HookServiceProviders.class));
    m_shutdown_hook = hooker.hookInitServiceProvider(new InitService());

  } // end initialize

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

  public void shutdown()
  {
    m_shutdown_hook.shutdown();

    Iterator it = m_connection_points.values().iterator();
    while (it.hasNext())
    { // shut down those connection points
      ComponentShutdown cs = (ComponentShutdown)(it.next());
      cs.shutdown();

    } // end while

    m_connection_points.clear();

  } // end shutdown

} // end class ConnectionManager
