/*
 * 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-03 Eric J. Bowersox/Silverwrist Design Studios.  All Rights Reserved.
 * 
 * Contributor(s): 
 */
package com.silverwrist.venice.app;

import java.util.*;
import org.apache.log4j.Logger;
import org.w3c.dom.*;
import com.silverwrist.util.xml.*;
import com.silverwrist.dynamo.db.UserPropertyTranslator;
import com.silverwrist.dynamo.db.UserPropertyTranslatorInstall;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.util.*;
import com.silverwrist.dynamo.velocity.VelocityRendererConfig;
import com.silverwrist.venice.VeniceNamespaces;
import com.silverwrist.venice.VeniceVersion;
import com.silverwrist.venice.content.*;
import com.silverwrist.venice.dialog.*;
import com.silverwrist.venice.frame.FrameAssembler;
import com.silverwrist.venice.iface.*;
import com.silverwrist.venice.menu.*;
import com.silverwrist.venice.script.*;
import com.silverwrist.venice.session.VeniceSessionManager;

public class VeniceApplication implements ComponentShutdown, Application, StylesheetMapper
{
  /*--------------------------------------------------------------------------------
   * Internal class implementing initialization code
   *--------------------------------------------------------------------------------
   */

  private class AppInit implements ComponentInitialize
  {
    /*====================================================================
     * Constructor
     *====================================================================
     */

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

    /*====================================================================
     * 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,"application");

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

	// load the stylesheet mappings
	Element sect = loader.getSubElement(config_root,"stylesheet-mappings");
	List l = loader.getMatchingSubElements(sect,"stylesheet");
	Iterator it = l.iterator();
	while (it.hasNext())
	{ // load the stylesheet mappings
	  Element elt = (Element)(it.next());
	  m_stylesheet_mappings.put(loader.getAttribute(elt,"path"),loader.getAttribute(elt,"prefix"));

	} // end while

	logger.info("Venice application '" + m_name + "' configuration initialized");

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

      } // end catch

      // Install the exception translator.
      ExceptionTranslatorRegistration etreg =
	  (ExceptionTranslatorRegistration)(services.queryService(ExceptionTranslatorRegistration.class));
      m_shutdown_list.addFirst(etreg.registerExceptionTranslator(new VeniceExceptionTranslator()));

      // Install the user property translator.
      UserPropertyTranslatorInstall upti =
          (UserPropertyTranslatorInstall)(GetObjectUtils.getDynamoComponent(services,
                                          UserPropertyTranslatorInstall.class,"users"));
      upti.installUserPropertyTranslator(new VeniceUserPropertyTranslator());

      // Customize the script engine.
      ScriptEngineConfig sconf = (ScriptEngineConfig)(services.queryService(ScriptEngineConfig.class));
      m_shutdown_list.addFirst(sconf.addDeclaredObject("vcast",new LibraryVeniceCast(),
						       LibraryVeniceCast.class));
      m_shutdown_list.addFirst(sconf.addDeclaredObject("vlib",new LibraryVenice(),LibraryVenice.class));

      // Customize the Velocity renderer.
      VelocityRendererConfig vrcon =
          (VelocityRendererConfig)(services.queryService(VelocityRendererConfig.class));
      m_shutdown_list.addFirst(vrcon.addStandardComponentClass("datefmt",DateFormatterTopHalf.class));

      // Done with initialization
      logger.info("Venice application '" + m_name + "' initialization done");

    } // end initialize

  } // end class AppInit

  /*--------------------------------------------------------------------------------
   * Static data members
   *--------------------------------------------------------------------------------
   */

  private static Logger logger = Logger.getLogger(VeniceApplication.class);

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

  private String m_name;                                    // the name of this object
  private HashMap m_stylesheet_mappings = new HashMap();    // stylesheet hash mappings
  private LinkedList m_shutdown_list = new LinkedList();    // shutdown list

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

  public VeniceApplication()
  {
    logger.info("Constructing new VeniceApplication");

  } // end constructor

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

  public void shutdown()
  {
    logger.info("Venice application '" + m_name + "' shutting down!");
    if (logger.isDebugEnabled())
      logger.debug("(" + m_shutdown_list.size() + " app-level component(s) to shutdown)");

    while (m_shutdown_list.size()>0)
    { // shut down all components on the shutdown list
      ComponentShutdown cs = (ComponentShutdown)(m_shutdown_list.removeFirst());
      cs.shutdown();

    } // end while

  } // end shutdown

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

  public String getName()
  {
    return m_name;

  } // end getName

  /*--------------------------------------------------------------------------------
   * 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==ComponentInitialize.class)
      return (ComponentInitialize)(new AppInit());
    if (klass==StylesheetMapper.class)
      return (StylesheetMapper)this;
    throw new NoSuchServiceException("VeniceApplication",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)
  {
    try
    { // try querying without the service ID
      return queryService(klass);

    } // end try
    catch (NoSuchServiceException e)
    { // throw a real exception
      throw new NoSuchServiceException(e.getContext(),klass,serviceid,e);

    } // end catch

  } // end queryService

  /*--------------------------------------------------------------------------------
   * Implementations from interface Application
   *--------------------------------------------------------------------------------
   */

  public String getIdentity()
  {
    return "Venice/" + VeniceVersion.VERSION;

  } // end getIdentity

  public Object getNullContentError(Request r)
  {
    return new ErrorBox(null,"Null content returned from request " + r.getContextPath()
			+ r.getRequestPath() + "!!");

  } // end getNullContentError

  /*--------------------------------------------------------------------------------
   * Implementations from interface StylesheetMapper
   *--------------------------------------------------------------------------------
   */

  public String getStylesheetPrefix(String path)
  {
    return (String)(m_stylesheet_mappings.get(path));

  } // end getStylesheetPrefix

} // end class VeniceApplication
