/*
 * 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) 2003 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.venice.VeniceNamespaces;
import com.silverwrist.venice.iface.*;

public class UserPhotoRenderer
    implements NamedObject, ComponentInitialize, ComponentShutdown, DynamicUpdateListener, ServiceProvider,
               RenderImage
{
  /*--------------------------------------------------------------------------------
   * Internal rendering object
   *--------------------------------------------------------------------------------
   */

  class RenderObject implements SelfRenderable
  {
    /*====================================================================
     * Attributes
     *====================================================================
     */

    private String m_url;

    /*====================================================================
     * Constructor
     *====================================================================
     */

    RenderObject(String url)
    {
      m_url = url;

    } // end constructor

    /*====================================================================
     * Implementations from interface SelfRenderable
     *====================================================================
     */

    public void render(SelfRenderControl control) throws IOException, RenderingException
    {
      renderImageTag(control.getTextRender(),m_url);

    } // end render

  } // end class RenderObject

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

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

  private static final String NAMESPACE = VeniceNamespaces.CONTENT_LAF_NAMESPACE;
  private static final String PROP_WIDTH = "user.photo.width";
  private static final String PROP_HEIGHT = "user.photo.height";

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

  private String m_name = null;             // object name
  private ObjectProvider m_props;           // pointer to global property provider
  private ComponentShutdown m_shut_event;   // event handler shutdown
  private int m_width;                      // width for user photos
  private int m_height;                     // height for user photos

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

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

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

  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(UserPhotoRenderer.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(UserPhotoRenderer.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("UserPhotoRenderer 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 UserPhotoRenderer",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(UserPhotoRenderer.class,"ContentMessages","init.noProp",e);

    } // end catch

    // Get the initial property values for our properties.
    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);

  } // end initialize

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

  public void shutdown()
  {
    m_shut_event.shutdown();
    m_shut_event = 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_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==RenderImage.class)
      return (RenderImage)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==RenderImage.class)
      return (RenderImage)this;
    throw new NoSuchServiceException(getName(),klass,serviceid);

  } // end queryService

  /*--------------------------------------------------------------------------------
   * Implementations from interface RenderImage
   *--------------------------------------------------------------------------------
   */

  public void renderImageTag(TextRenderControl control, String url) throws IOException, RenderingException
  {
    PrintWriter wr = control.getWriter();
    wr.write("<img src=\"" + url + "\" alt=\"\" width=\"" + m_width + "\" height=\"" + m_height
	     + "\" border=\"0\" />");

  } // end renderImageTag

  public Object getRenderingObject(String url)
  {
    return new RenderObject(url);

  } // end getRenderingObject

} // end class UserPhotoRenderer
