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

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

public class ScriptDispatcher implements ComponentInitialize, XmlRpcDispatcher
{
  /*--------------------------------------------------------------------------------
   * Attributes
   *--------------------------------------------------------------------------------
   */

  private String m_script_name;
  private String m_session_param = null;
  private Hashtable m_metadata = new Hashtable();

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

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

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

  private final void loadMetadataList(List l) throws ConfigException
  {
    Iterator it = l.iterator();
    while (it.hasNext())
    { // create metadata elements
      Element elt = (Element)(it.next());
      XMLMetadata md = new XMLMetadata(elt);
      m_metadata.put(md.getMethodName(),md);

    } // end while

  } // end loadMetadataList

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

  public void initialize(Element config_root, ServiceProvider services) throws ConfigException
  {
    XMLLoader loader = XMLLoader.get();
    try
    { // get the script name
      DOMElementHelper config_root_h = new DOMElementHelper(config_root);
      m_script_name = loader.getSubElementText(config_root_h,"script");

      // get the session parameter
      Element elt = config_root_h.getSubElement("session");
      if (elt!=null)
	m_session_param = loader.getAttribute(elt,"param");

      // load a metadata file if it's present
      String md_file = config_root_h.getSubElementText("metadata-file");
      if (md_file!=null)
      { // try and load the metadata file
	InputStream stm = null;
	try
	{ // load the resource and parse it into XML
	  ResourceProvider rprov = (ResourceProvider)(services.queryService(ResourceProvider.class));
	  stm = rprov.getResource(md_file);
	  Document doc = loader.load(stm,false);
	  Element md_root = loader.getRootElement(doc,"metadata-file");
	  loadMetadataList(loader.getMatchingSubElements(md_root,"metadata"));

	} // end try
	catch (NoSuchResourceException e)
	{ // just ignore the file
	} // end catch
	catch (IOException e)
	{ // just ignore the file
	} // end catch
	finally
	{ // shut down stream
	  IOUtils.shutdown(stm);

	} // end finally

      } // end if (metadata file specified)

      // load direct metadata if it's present
      loadMetadataList(loader.getMatchingSubElements(config_root,"metadata"));

    } // end try
    catch (XMLLoadException e)
    { // translate to ConfigException
      throw new ConfigException(e);

    } // end catch

  } // end initialize

  /*--------------------------------------------------------------------------------
   * Implementations from interface XmlRpcDispatcher
   *--------------------------------------------------------------------------------
   */

  public String getSessionIDParamValue(Request r, Application app)
  {
    if (m_session_param==null)
      return null;
    Object o = r.getParameters().get(m_session_param);
    return ((o==null) ? null : o.toString());

  } // end getSessionIDParamValue

  public Object dispatchXmlRpcCall(Request r, Application app) throws Exception, FaultCode
  {
    ScriptExecute exec = (ScriptExecute)(r.queryService(ScriptExecute.class));
    return exec.executeScript(r,m_script_name);

  } // end dispatchXmlRpcCall

  public Collection getSupportedMethods(Request r)
  {
    return Collections.unmodifiableSet(m_metadata.keySet());

  } // end getSupportedMethods

  public List getMethodSignature(Request r, String method) throws FaultCode
  {
    XMLMetadata md = (XMLMetadata)(m_metadata.get(method));
    if (md!=null)
      return md.getSignatures();
    else
      return null;

  } // end getMethodSignature

  public String getMethodHelp(Request r, String method) throws FaultCode
  {
    XMLMetadata md = (XMLMetadata)(m_metadata.get(method));
    if (md!=null)
      return md.getDocumentation();
    else
      return "";

  } // end getMethodHelp

} // end class ScriptDispatcher
