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

import org.w3c.dom.*;
import com.silverwrist.util.xml.*;
import com.silverwrist.dynamo.db.UserProxyManagement;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.util.*;
import com.silverwrist.venice.session.SessionInfoParams;

public class FederationManagerObject implements NamedObject, ComponentInitialize, ComponentShutdown, FederationManager
{
  /*--------------------------------------------------------------------------------
   * Internal class implementing library operations.
   *--------------------------------------------------------------------------------
   */

  private class MyLib extends LibrarySourceID
  {
    /*====================================================================
     * Constructor
     *====================================================================
     */

    MyLib()
    {
      super();

    } // end constructor

    /*====================================================================
     * Abstract implementations from class LibrarySourceID
     *====================================================================
     */

    public boolean isUserFederatedWith(Request r, String providerID) throws DatabaseException
    {
      SessionInfoProvider sip = (SessionInfoProvider)(r.queryService(SessionInfoProvider.class));
      SessionInfo si = sip.getSessionInfo();
      DynamoUser user = (DynamoUser)(si.getObject(SessionInfoParams.NAMESPACE,SessionInfoParams.ATTR_USER));
      String[] rc = FederationManagerObject.this.getFederatedNames(user,providerID);
      return (rc!=null);

    } // end isUserFederatedWith

  } // end class MyLib

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

  private String m_name;                                    // object name
  private VeniceAccountOps m_ops = null;                    // account operations
  private UserProxyManagement m_upm = null;                 // user proxy operations
  private ComponentShutdown m_lib_shutdown;                 // to shut down the library

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

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

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

  public String getName()
  {
    return m_name;

  } // end getName

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

  public void initialize(Element config_root, ServiceProvider services) throws ConfigException
  {
    String conn_name = null;
    String proxy_name = null;
    XMLLoader loader = XMLLoader.get();
    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 database configuration connection
      DOMElementHelper config_root_h = new DOMElementHelper(config_root);
      Element elt = loader.getSubElement(config_root_h,"database");
      conn_name = loader.getAttribute(elt,"connection");
      proxy_name = loader.getAttribute(elt,"userproxy");

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

    } // end catch

    // Get the database connection pool and user proxy.
    DBConnectionPool pool = GetObjectUtils.getDatabaseConnection(services,conn_name);
    m_upm = (UserProxyManagement)(GetObjectUtils.getDynamoComponent(services,UserProxyManagement.class,proxy_name));

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

    // Install our script library as a declared object.
    ScriptEngineConfig cfg = (ScriptEngineConfig)(services.queryService(ScriptEngineConfig.class));
    m_lib_shutdown = cfg.addDeclaredObject("sourceid",new MyLib(),LibrarySourceID.class);

  } // end initialize

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

  public void shutdown()
  {
    m_lib_shutdown.shutdown();
    m_lib_shutdown = null;
    m_upm = null;
    m_ops.dispose();
    m_ops = null;

  } // end shutdown

  /*--------------------------------------------------------------------------------
   * Implementations from interface FederationManager
   *--------------------------------------------------------------------------------
   */

  public void addFederation(DynamoUser user, String providerID, String local_name, String remote_name)
      throws DatabaseException
  {
    m_ops.addFederation(user.getUID(),providerID,local_name,remote_name);

  } // end addFederation

  public void removeFederation(DynamoUser user, String providerID) throws DatabaseException
  {
    m_ops.removeFederation(user.getUID(),providerID);

  } // end removeFederation

  public DynamoUser lookupFederatedUser(String providerID, String name, boolean search_local) throws DatabaseException
  {
    int uid = -1;
    if (search_local)
      uid = m_ops.lookupByLocalName(providerID,name);
    else
      uid = m_ops.lookupByRemoteName(providerID,name);
    if (uid<=0)
      return null;
    return m_upm.getUserProxy(uid);

  } // end lookupFederatedUser

  public String[] getFederatedNames(DynamoUser user, String providerID) throws DatabaseException
  {
    return m_ops.getNames(user.getUID(),providerID);

  } // end getFederatedNames

} // end class FederationManagerObject
