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

import java.io.*;
import org.apache.log4j.Logger;
import org.w3c.dom.*;
import com.silverwrist.util.xml.*;
import com.silverwrist.dynamo.event.*;
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.ButtonType;
import com.silverwrist.venice.VeniceNamespaces;
import com.silverwrist.venice.iface.*;

public class ButtonSupplier
    implements NamedObject, ComponentInitialize, ComponentShutdown, DynamicUpdateListener, ServiceProvider,
               ButtonProvider, TextRenderer
{
  /*--------------------------------------------------------------------------------
   * Internal class implementing Velocity button provider
   *--------------------------------------------------------------------------------
   */

  public class StdButton
  {
    /*====================================================================
     * Constructor
     *====================================================================
     */

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

    /*====================================================================
     * External operations
     *====================================================================
     */

    public Object getButton(String type, String name)
    {
      return getButtonRenderObject(ButtonType.getEnum(type.trim().toUpperCase()),name);

    } // end getButton

  } // end class StdButton

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

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

  private static final String NAMESPACE = VeniceNamespaces.CONTENT_LAF_NAMESPACE;

  private static final String PROP_SUBDIR = "subdir.buttons";
  private static final String PROP_WIDTH = "std.button.width";
  private static final String PROP_HEIGHT = "std.button.height";
  private static final String PROP_PREFIX_BUTTON = "bn.";
  private static final String PROP_PREFIX_CAPTION = "bnc.";

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

  private String m_name = null;              // name of this object
  private ObjectProvider m_props;            // property set provider
  private ComponentShutdown m_shut_event;    // shutdown for event listener
  private ComponentShutdown m_shut_render;   // shutdown for renderer
  private ComponentShutdown m_shut_vr;       // shutdown for Velocity object
  private String m_subdir;                   // subdirectory in which button images are
  private int m_width;                       // width of buttons
  private int m_height;                      // height of buttons

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

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

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

  private final String getInitString(String name) throws ConfigException
  {
    try
    { // call through to the property provider
      return (String)(m_props.getObject(NAMESPACE,name));

    } // end try
    catch (NoSuchObjectException e)
    { // the property value isn't present?  yIkes!
      ConfigException ce = new ConfigException(ButtonSupplier.class,"ContentMessages","prop.missing",e);
      ce.setParameter(0,name);
      throw ce;

    } // end catch
    catch (ClassCastException e)
    { // not a String?  for shame!
      ConfigException ce = new ConfigException(ButtonSupplier.class,"ContentMessages","prop.wrongType",e);
      ce.setParameter(0,name);
      throw ce;

    } // end catch

  } // end getInitString

  private final int getInitInteger(String name) throws ConfigException
  {
    try
    { // call through to the property provider
      return ((Integer)(m_props.getObject(NAMESPACE,name))).intValue();

    } // end try
    catch (NoSuchObjectException e)
    { // the property value isn't present?  yIkes!
      ConfigException ce = new ConfigException(ButtonSupplier.class,"ContentMessages","prop.missing",e);
      ce.setParameter(0,name);
      throw ce;

    } // end catch
    catch (ClassCastException e)
    { // not an Integer?  for shame!
      ConfigException ce = new ConfigException(ButtonSupplier.class,"ContentMessages","prop.wrongType",e);
      ce.setParameter(0,name);
      throw ce;

    } // end catch

  } // end getInitInteger

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

  public String getName()
  {
    return m_name;

  } // end getName

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

  /**
   * Initialize the component.
   *
   * @param config_root Pointer to the section of the Dynamo XML configuration file that configures this
   *                    particular component.  This is to be considered "read-only" by the component.
   * @param services An implementation of {@link com.silverwrist.dynamo.iface.ServiceProvider ServiceProvider}
   *                 which provides initialization services to the component.  This will include an implementation
   *                 of {@link com.silverwrist.dynamo.iface.ObjectProvider ObjectProvider} which may be used to
   *                 get information about other objects previously initialized by the application.
   * @exception com.silverwrist.dynamo.except.ConfigException If an error is encountered in the component
   *            configuration.
   */
  public void initialize(Element config_root, ServiceProvider services) throws ConfigException
  {
    logger.info("ButtonSupplier initializing");

    XMLLoader loader = XMLLoader.get();
    String gprops = null;
    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 name of the global properties object
      DOMElementHelper config_root_h = new DOMElementHelper(config_root);
      Element foo = loader.getSubElement(config_root_h,"global-properties");
      gprops = loader.getAttribute(foo,"object");

    } // end try
    catch (XMLLoadException e)
    { // error loading XML config data
      logger.fatal("XML loader exception in ButtonSupplier",e);
      throw new ConfigException(e);

    } // end catch

    // Get the standard properties provider.
    ServiceProvider gdm_sp =
        (ServiceProvider)(GetObjectUtils.getDynamoComponent(services,ServiceProvider.class,gprops));
    try
    { // get the "properties" service from that object
      m_props = (ObjectProvider)(gdm_sp.queryService(ObjectProvider.class,"properties"));

    } // end try
    catch (NoSuchServiceException e)
    { // this shouldn't happen, but...
      logger.fatal("Unable to find global properties object \"" + gprops + "\"",e);
      throw new ConfigException(ButtonSupplier.class,"ContentMessages","init.noProp",e);

    } // end catch

    // Get the initial property values for our most used properties.
    m_subdir = getInitString(PROP_SUBDIR);
    m_width = getInitInteger(PROP_WIDTH);
    m_height = getInitInteger(PROP_HEIGHT);

    // Register with the event listener to monitor those property values.
    EventListenerRegistration reg =
        (EventListenerRegistration)(services.queryService(EventListenerRegistration.class));
    m_shut_event = reg.registerDynamicUpdateListener(GlobalPropertyUpdateEvent.class,this);

    // Register us as being a renderer for ButtonToken objects (which we generate).
    RendererRegistration rr = (RendererRegistration)(services.queryService(RendererRegistration.class));
    m_shut_render = rr.registerRenderer(ButtonToken.class,this);

    // Add an object to the standard objects available to Velocity.
    VelocityRendererConfig vrcon =
        (VelocityRendererConfig)(services.queryService(VelocityRendererConfig.class));
    m_shut_vr = vrcon.addStandardComponentInstance("button",new StdButton());

  } // end initialize

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

  public void shutdown()
  {
    m_shut_vr.shutdown();
    m_shut_vr = null;
    m_shut_event.shutdown();
    m_shut_event = null;
    m_shut_render.shutdown();
    m_shut_render = null;
    m_props = null;

  } // end shutdown

  /*--------------------------------------------------------------------------------
   * Implementations from interface DynamicUpdateListener
   *--------------------------------------------------------------------------------
   */

  public void updateReceived(DynamicUpdateEvent evt)
  {
    GlobalPropertyUpdateEvent event = (GlobalPropertyUpdateEvent)evt;
    if (NAMESPACE.equals(event.getPropertyNamespace()))
    { // see if this is one of the properties we monitor
      try
      { // reuse the "initialization" getters here
	if (PROP_SUBDIR.equals(event.getPropertyName()))
	{ // process new subdirectory
	  String s = getInitString(PROP_SUBDIR);
	  m_subdir = s;

	} // end if
	else if (PROP_WIDTH.equals(event.getPropertyName()))
	{ // process new width
	  int x = getInitInteger(PROP_WIDTH);
	  m_width = x;

	} // end else if
	else if (PROP_HEIGHT.equals(event.getPropertyName()))
	{ // process new height
	  int x = getInitInteger(PROP_HEIGHT);
	  m_height = x;

	} // end else if

      } // end try
      catch (ConfigException ce)
      { // property get failed - don't change the value
      } // end catch

    } // end if

  } // end updateReceived

  /*--------------------------------------------------------------------------------
   * 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==ButtonProvider.class)
      return (ButtonProvider)this;
    throw new NoSuchServiceException(getName(),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==ButtonProvider.class)
      return (ButtonProvider)this;
    throw new NoSuchServiceException(getName(),klass,serviceid);

  } // end queryService

  /*--------------------------------------------------------------------------------
   * Implementations from interface ButtonProvider
   *--------------------------------------------------------------------------------
   */

  public Object getButtonRenderObject(ButtonType type, String name)
  {
    try
    { // get the button image name and return our object
      String image_name = (String)(m_props.getObject(NAMESPACE,PROP_PREFIX_BUTTON + name));
      String caption = (String)(m_props.getObject(NAMESPACE,PROP_PREFIX_CAPTION + name));
      return new ButtonToken(type,name,image_name,caption);

    } // end try
    catch (NoSuchObjectException e)
    { // encapsulate the error message so we'll get it later
      RenderingException re = new RenderingException(ButtonSupplier.class,"ContentMessages",
						     "button.missing",e);
      re.setParameter(0,name);
      return new RenderingExceptionWrapper(re);

    } // end catch
    catch (ClassCastException e)
    { // encapsulate the error message so we'll get it later
      RenderingException re = new RenderingException(ButtonSupplier.class,"ContentMessages",
						     "button.wrongType",e);
      re.setParameter(0,name);
      return new RenderingExceptionWrapper(re);

    } // end catch

  } // end getButtonRenderObject

  /*--------------------------------------------------------------------------------
   * Implementations from interface TextRenderer
   *--------------------------------------------------------------------------------
   */

  public void render(Object obj, TextRenderControl control) throws IOException, RenderingException
  {
    URLRewriter rewrite = (URLRewriter)(control.queryService(URLRewriter.class));
    PrintWriter wr = control.getWriter();
    ButtonToken token = (ButtonToken)obj;

    // get the full URL of the image
    String image_url = rewrite.rewriteURL("IMAGE",m_subdir + "/" + token.getImageName());

    // render as <image/> tag
    if (ButtonType.IMAGE.equals(token.getType()))
      wr.write("<img src=\"" + image_url + "\" alt=\"[" + token.getCaption() + "]\" width = \"" + m_width
	       + "\" height=\"" + m_height + "\" border=\"0\" />");

    // render as <input type="image"/> tag
    if (ButtonType.INPUT.equals(token.getType()))
      wr.write("<input type=\"image\" src=\"" + image_url + "\" name=\"" + token.getName() + "\" alt=\""
	       + token.getCaption() + "\" width=\"" + m_width + "\" height=\"" + m_height
	       + "\" border=\"0\" />");

  } // end render

} // end class ButtonSupplier
