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

import java.util.*;
import org.apache.log4j.Logger;
import org.w3c.dom.*;
import com.silverwrist.util.xml.*;
import com.silverwrist.dynamo.db.NamespaceCache;
import com.silverwrist.dynamo.db.UserManagement;
import com.silverwrist.dynamo.db.UserProxyManagement;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.security.SecurityReferenceMonitor;
import com.silverwrist.dynamo.util.*;
import com.silverwrist.venice.SearchMode;
import com.silverwrist.venice.UserSearchField;
import com.silverwrist.venice.VeniceNamespaces;

public class AdvancedUserManager implements NamedObject, ComponentInitialize, ComponentShutdown, AdvancedUserService
{
  /*--------------------------------------------------------------------------------
   * Static data members
   *--------------------------------------------------------------------------------
   */

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

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

  private String m_name;                       // this object's name
  private AdvancedUserOps m_ops;               // database operations
  private NamespaceCache m_ns_cache;           // namespace cache object
  private SecurityReferenceMonitor m_srm;      // security reference monitor
  private UserManagement m_users;              // user management object
  private UserProxyManagement m_proxy;         // user proxy management object

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

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

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

  private final List translateUIDArray(int[] uids)
  {
    if ((uids==null) || (uids.length==0))
      return Collections.EMPTY_LIST;
    ArrayList rc = new ArrayList(uids.length);
    for (int i=0; i<uids.length; i++)
      rc.add(m_proxy.getUserProxy(uids[i]));
    return Collections.unmodifiableList(rc);

  } // end translateUIDArray

  /*--------------------------------------------------------------------------------
   * 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("AdvancedUserManager initializing");

    XMLLoader loader = XMLLoader.get();
    String name_pool = null, name_nscache = null, name_srm = null, name_users = 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 database pool and namespace cache
      DOMElementHelper config_root_h = new DOMElementHelper(config_root);
      Element foo = loader.getSubElement(config_root_h,"database");
      name_pool = loader.getAttribute(foo,"connection");
      name_nscache = loader.getAttribute(foo,"namespaces");

      // get the name of the security reference monitor
      foo = loader.getSubElement(config_root_h,"security");
      name_srm = loader.getAttribute(foo,"object");

      // get the name of the user manager
      foo = loader.getSubElement(config_root_h,"user-manager");
      name_users = loader.getAttribute(foo,"object");

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

    } // end catch

    // Get the database connection pool.
    DBConnectionPool pool = GetObjectUtils.getDatabaseConnection(services,name_pool);

    // Get the database operations object.
    m_ops = AdvancedUserOps.get(pool);

    // Get the namespace cache.
    m_ns_cache = (NamespaceCache)(GetObjectUtils.getDynamoComponent(services,NamespaceCache.class,name_nscache));

    // Get the security reference monitor.
    m_srm = (SecurityReferenceMonitor)(GetObjectUtils.getDynamoComponent(services,SecurityReferenceMonitor.class,
									 name_srm));

    // Get the user management object.
    m_users = (UserManagement)(GetObjectUtils.getDynamoComponent(services,UserManagement.class,name_users));
    m_proxy = (UserProxyManagement)(GetObjectUtils.getDynamoComponent(services,UserProxyManagement.class,name_users));

  } // end initialize

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

  public void shutdown()
  {
    m_proxy = null;
    m_users = null;
    m_srm = null;
    m_ns_cache = null;
    m_ops.dispose();
    m_ops = null;

  } // end shutdown

  /*--------------------------------------------------------------------------------
   * Implementations from interface UserManagement
   *--------------------------------------------------------------------------------
   */

  public DynamoUser getAnonymousUser() throws DatabaseException
  {
    return m_users.getAnonymousUser();

  } // end getAnonymousUser

  public DynamoUser getUser(int id) throws DatabaseException
  {
    return m_users.getUser(id);

  } // end getUser

  public DynamoUser getUser(String username) throws DatabaseException
  {
    return m_users.getUser(username);

  } // end getUser

  public DynamoUser createUser(String username, String email) throws DatabaseException
  {
    return m_users.createUser(username,email);

  } // end createUser

  public DynamoGroup getGroup(int id) throws DatabaseException
  {
    return m_users.getGroup(id);

  } // end getGroup

  public DynamoGroup getGroup(String groupname) throws DatabaseException
  {
    return m_users.getGroup(groupname);

  } // end getGroup

  public DynamoGroup createGroup(String groupname) throws DatabaseException
  {
    return m_users.createGroup(groupname);

  } // end createGroup

  public void loadUserDefaults(DynamoUser user, Collection namespaces) throws DatabaseException
  {
    m_users.loadUserDefaults(user,namespaces);

  } // end loadUserDefaults

  /*--------------------------------------------------------------------------------
   * Implementations from interface AdvancedUserService
   *--------------------------------------------------------------------------------
   */

  public List searchForUsers(DynamoUser caller, UserSearchField field, SearchMode mode, String term,
			     int offset, int count) throws DatabaseException
  {
    int[] rc = null;
    String prop = null;
    if (UserSearchField.USERNAME.equals(field))
      rc = m_ops.searchName(mode,term,offset,count);
    else if (UserSearchField.DESCRIPTION.equals(field))
      prop = "description";
    else if (UserSearchField.FIRSTNAME.equals(field))
      prop = "name.given";
    else if (UserSearchField.LASTNAME.equals(field))
      prop = "name.family";
    else
      throw new IllegalArgumentException("invalid search field (shouldn't happen)");
    if ((rc==null) && (prop!=null))
      rc = m_ops.searchProperty(m_ns_cache.namespaceNameToId(VeniceNamespaces.USER_PROFILE_NAMESPACE),prop,mode,
				term,offset,count);
    return translateUIDArray(rc);

  } // end searchForUsers

  public int getSearchUserCount(DynamoUser caller, UserSearchField field, SearchMode mode, String term)
      throws DatabaseException
  {
    String prop = null;
    if (UserSearchField.USERNAME.equals(field))
      return m_ops.searchNameCount(mode,term);
    else if (UserSearchField.DESCRIPTION.equals(field))
      prop = "description";
    else if (UserSearchField.FIRSTNAME.equals(field))
      prop = "name.given";
    else if (UserSearchField.LASTNAME.equals(field))
      prop = "name.family";
    else
      throw new IllegalArgumentException("invalid search field (shouldn't happen)");
    return m_ops.searchPropertyCount(m_ns_cache.namespaceNameToId(VeniceNamespaces.USER_PROFILE_NAMESPACE),
				     prop,mode,term);

  } // end getSearchUserCount

  public List searchForMembers(DynamoUser caller, DynamoGroup group, UserSearchField field, SearchMode mode,
			       String term, int offset, int count) throws DatabaseException
  {
    int[] rc = null;
    String prop = null;
    if (UserSearchField.USERNAME.equals(field))
      rc = m_ops.searchName(group.getGID(),mode,term,offset,count);
    else if (UserSearchField.DESCRIPTION.equals(field))
      prop = "description";
    else if (UserSearchField.FIRSTNAME.equals(field))
      prop = "name.given";
    else if (UserSearchField.LASTNAME.equals(field))
      prop = "name.family";
    else
      throw new IllegalArgumentException("invalid search field (shouldn't happen)");
    if ((rc==null) && (prop!=null))
      rc = m_ops.searchProperty(group.getGID(),m_ns_cache.namespaceNameToId(VeniceNamespaces.USER_PROFILE_NAMESPACE),
				prop,mode,term,offset,count);
    return translateUIDArray(rc);

  } // end searchForMembers

  public int getSearchMemberCount(DynamoUser caller, DynamoGroup group, UserSearchField field, SearchMode mode,
				  String term) throws DatabaseException
  {
    String prop = null;
    if (UserSearchField.USERNAME.equals(field))
      return m_ops.searchNameCount(group.getGID(),mode,term);
    else if (UserSearchField.DESCRIPTION.equals(field))
      prop = "description";
    else if (UserSearchField.FIRSTNAME.equals(field))
      prop = "name.given";
    else if (UserSearchField.LASTNAME.equals(field))
      prop = "name.family";
    else
      throw new IllegalArgumentException("invalid search field (shouldn't happen)");
    return m_ops.searchPropertyCount(group.getGID(),
				     m_ns_cache.namespaceNameToId(VeniceNamespaces.USER_PROFILE_NAMESPACE),
				     prop,mode,term);

  } // end getSearchMemberCount

} // end class AdvancedUserManager
