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

import java.util.*;
import org.apache.commons.collections.*;
import com.silverwrist.dynamo.UserInfoNamespace;
import com.silverwrist.dynamo.event.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.security.SecurityReferenceMonitor;
import com.silverwrist.dynamo.util.*;

class UserObject implements DynamoUser, UserInfoNamespace
{
  /*--------------------------------------------------------------------------------
   * Attributes
   *--------------------------------------------------------------------------------
   */

  private UserObjectOps m_ops;                      // operations object
  private NamespaceCache m_ns_cache;                // namespace cache object
  private SecurityReferenceMonitor m_srm;           // security reference monitor
  private AuthenticatorLookup m_auth_lookup;        // authenticator lookup
  private PostDynamicUpdate m_post;                 // where we post dynamic events
  private UserPropertyTranslator m_upt;
  private int m_uid;                                // user ID
  private String m_username;                        // user name
  private String m_email;                           // E-mail address
  private java.util.Date m_created;                 // created date
  private java.util.Date m_last_accessed;           // last access date
  private boolean m_anonymous;                      // is this the anonymous user?
  private boolean m_locked;                         // is user locked?
  private boolean m_nospam;                         // user "no-spam" flag
  private ReferenceMap m_properties;                // cached property values
  private Object m_properties_sync = new Object();  // synchronization for above

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

  UserObject(Map data, boolean anonymous, UserObjectOps ops, NamespaceCache ns_cache,
	     SecurityReferenceMonitor srm, AuthenticatorLookup auth_lookup, PostDynamicUpdate post,
	     UserPropertyTranslator upt)
  {
    m_ops = ops;
    m_ns_cache = ns_cache;
    m_srm = srm;
    m_auth_lookup = auth_lookup;
    m_post = post;
    m_upt = upt;
    m_uid = ((Integer)(data.get(UserManagerOps.HMKEY_UID))).intValue();
    m_username = (String)(data.get(UserManagerOps.HMKEY_USERNAME));
    m_email = (String)(data.get(UserManagerOps.HMKEY_EMAIL));
    m_created = (java.util.Date)(data.get(UserManagerOps.HMKEY_CREATED));
    m_last_accessed = (java.util.Date)(data.get(UserManagerOps.HMKEY_LAST_ACCESS));
    m_anonymous = anonymous;
    m_locked = ((Boolean)(data.get(UserManagerOps.HMKEY_LOCKED))).booleanValue();
    m_nospam = ((Boolean)(data.get(UserManagerOps.HMKEY_NOSPAM))).booleanValue();
    m_properties = new ReferenceMap(ReferenceMap.HARD,ReferenceMap.SOFT);

  } // end constructor

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

  private final void testChangeOK(DynamoUser caller) throws DatabaseException, DynamoSecurityException
  {
    if (equals(caller))
      return;  // a user can always change their OWN information

    if (caller.equals(m_srm.getAdminUser()))
      return;  // Administrator can do anything

    if (m_srm.getGlobalAcl().testPermission(caller,NAMESPACE,PERM_EDIT_ALL))
      return;  // and so can anyone else with "edit all" permission on the global ACL

    // Presume the change is forbidden - throw the exception
    DynamoSecurityException dse = new DynamoSecurityException(UserObject.class,"DatabaseMessages",
							      "sec.changeUser");
    dse.setParameter(0,m_username);
    throw dse;

  } // end testChangeOK

  /*--------------------------------------------------------------------------------
   * Implementations from interface Principal
   *--------------------------------------------------------------------------------
   */

  public boolean equals(Object another)
  {
    if (another==null)
      return false;
    if (another instanceof DynamoUser)
      return (m_uid==((DynamoUser)another).getUID());
    return false;

  } // end equals

  public String toString()
  {
    return "user " + m_username;

  } // end toString

  public int hashCode()
  {
    return m_uid;

  } // end hashCode

  public String getName()
  {
    return m_username;

  } // end getName

  /*--------------------------------------------------------------------------------
   * Implementations from interface ObjectProvider
   *--------------------------------------------------------------------------------
   */

  /**
   * Retrieves an object from this <CODE>ObjectProvider</CODE>.
   *
   * @param namespace The namespace to interpret the name relative to.
   * @param name The name of the object to be retrieved.
   * @return The object reference specified.
   */
  public Object getObject(String namespace, String name)
  {
    if (NAMESPACE.equals(namespace))
    { // handle user info namespace specially
      if (ATTR_FULLNAME.equals(name))
	return m_upt.getUserFullName(this);
      else if (ATTR_EMAIL_ADDRESS.equals(name))
	return m_email;
      else if (ATTR_ID.equals(name))
	return new Integer(m_uid);
      else if (ATTR_USERNAME.equals(name))
	return m_username;
      else
	throw new NoSuchObjectException(this.toString(),namespace,name);

    } // end if

    try
    { // convert the namespace name to an ID here
      PropertyKey key = new PropertyKey(m_ns_cache.namespaceNameToId(namespace),name);
      Object rc = null;
      synchronized (m_properties_sync)
      { // start by looking in the properties map
	rc = m_properties.get(key);
	if (rc==null)
	{ // no use - need to try the database
	  rc = m_ops.getProperty(m_uid,key);
	  if (rc!=null)
	    m_properties.put(key,rc);

	} // end if

      } // end synchronized block

      if (rc==null)
	throw new NoSuchObjectException(this.toString(),namespace,name);
      return rc;

    } // end try
    catch (DatabaseException e)
    { // translate into our NoSuchObjectException but retain the DatabaseException
      throw new NoSuchObjectException(this.toString(),namespace,name,e);

    } // end catch

  } // end getObject

  /*--------------------------------------------------------------------------------
   * Implementations from interface SecureObjectStore
   *--------------------------------------------------------------------------------
   */

  public Object setObject(DynamoUser caller, String namespace, String name, Object value)
      throws DatabaseException, DynamoSecurityException
  {
    if (NAMESPACE.equals(namespace))
    { // can't set more data in restricted namespace
      ObjectStoreException ose = new ObjectStoreException(UserObject.class,"DatabaseMessages",
							  "ose.setProperty");
      ose.setParameter(0,namespace);
      ose.setParameter(1,name);
      throw ose;

    } // end if

    testChangeOK(caller);
    Object rc = null;

    // convert the namespace name to an ID here
    PropertyKey key = new PropertyKey(m_ns_cache.namespaceNameToId(namespace),name);
    synchronized (m_properties_sync)
    { // start by setting the database value
      rc = m_ops.setProperty(m_uid,key,value);

      // and cache it, too
      m_properties.put(key,value);

    } // end synchronized block

    m_post.postUpdate(new UserPropertyUpdateEvent(this,m_uid,namespace,name));
    return rc;

  } // end setObject

  public Object removeObject(DynamoUser caller, String namespace, String name)
      throws DatabaseException, DynamoSecurityException
  {
    if (NAMESPACE.equals(namespace))
    { // can't set more data in restricted namespace
      ObjectStoreException ose = new ObjectStoreException(UserObject.class,"DatabaseMessages",
							  "ose.removeProperty");
      ose.setParameter(0,namespace);
      ose.setParameter(1,name);
      throw ose;

    } // end if

    testChangeOK(caller);
    Object rc = null;
    // convert the namespace name to an ID here
    PropertyKey key = new PropertyKey(m_ns_cache.namespaceNameToId(namespace),name);
    synchronized (m_properties_sync)
    { // start by killing the database value
      rc = m_ops.removeProperty(m_uid,key);

      // and remove the cached value, too
      m_properties.remove(key);

    } // end synchronized block

    m_post.postUpdate(new UserPropertyUpdateEvent(this,m_uid,namespace,name));
    return rc;

  } // end removeObject

  public Collection getNamespaces() throws DatabaseException
  {
    // call through to the database to get the list of namespace IDs
    int[] ids = m_ops.getPropertyNamespaceIDs(m_uid);

    ArrayList rc = new ArrayList(ids.length);
    for (int i=0; i<ids.length; i++)
      rc.add(m_ns_cache.namespaceIdToName(ids[i]));
    rc.add(NAMESPACE);
    return Collections.unmodifiableList(rc);

  } // end getNamespaces

  public Collection getNamesForNamespace(String namespace) throws DatabaseException
  {
    if (NAMESPACE.equals(namespace))
    { // return the "static" attribute names
      ArrayList rc = new ArrayList();
      rc.add(ATTR_FULLNAME);
      rc.add(ATTR_EMAIL_ADDRESS);
      rc.add(ATTR_ID);
      rc.add(ATTR_USERNAME);
      return Collections.unmodifiableList(rc);

    } // end if

    // call through to the database to get the data for this namespace
    int nsid = m_ns_cache.namespaceNameToId(namespace);
    Map data = m_ops.getAllProperties(m_uid,nsid);

    // we both create the return value and cache the data values
    ArrayList rc = new ArrayList(data.size());
    synchronized (m_properties_sync)
    { // do the transfer...
      Iterator it = data.entrySet().iterator();
      while (it.hasNext())
      { // copy one entry at a time
	Map.Entry ntry = (Map.Entry)(it.next());
	rc.add(ntry.getKey().toString());
	m_properties.put(new PropertyKey(nsid,ntry.getKey().toString()),ntry.getValue());

      } // end while

    } // end synchronized block

    return Collections.unmodifiableList(rc);

  } // end getNamesForNamespace

  /*--------------------------------------------------------------------------------
   * Implementations from interface DynamoUser
   *--------------------------------------------------------------------------------
   */

  public int getUID()
  {
    return m_uid;

  } // end getUID

  public boolean isAnonymous()
  {
    return m_anonymous;

  } // end isAnonymous

  public boolean isLocked()
  {
    return m_locked;

  } // end isLocked

  public void setLocked(DynamoUser caller, boolean locked) throws DatabaseException, DynamoSecurityException
  {
    testChangeOK(caller);
    if (m_anonymous)
      return;  // cannot change lock status for anonymous user
    if (m_locked!=locked)
    { // call through to set the flag
      m_ops.setLocked(m_uid,locked);
      m_locked = locked;

    } // end if

  } // end setLocked

  public boolean isNoSpam()
  {
    return m_nospam;

  } // end isNoSpam

  public void setNoSpam(DynamoUser caller, boolean nospam) throws DatabaseException, DynamoSecurityException
  {
    testChangeOK(caller);
    if (m_anonymous)
      return;  // cannot change nospam status for anonymous user
    if (m_nospam!=nospam)
    { // call through to set the flag
      m_ops.setNoSpam(m_uid,nospam);
      m_nospam = nospam;

    } // end if

  } // end setNoSpam

  public String getEMailAddress()
  {
    return m_email;

  } // end getEMailAddress

  public boolean setEMailAddress(DynamoUser caller, String addr)
      throws DatabaseException, DynamoSecurityException
  {
    testChangeOK(caller);
    if (m_anonymous)
      return false;  // cannot change E-mail address for anonymous user
    if (m_email.equals(addr))
      return false;  // no change necessary
    m_ops.setEMailAddress(m_uid,addr);
    m_email = addr;
    return true;

  } // end setEMailAddress

  public boolean authenticate(String method_namespace, String method, String source_data, String auth_data)
      throws DatabaseException, AuthenticationException
  {
    if (m_anonymous)
      return false;  // anonymous user cannot authenticate

    // Get the authenticator that handles these requests.
    Authenticator auth = m_auth_lookup.findAuthenticator(method_namespace,method);
    if (auth==null)
    { // the authenticator could not be found - bail out
      AuthenticationException ae = new AuthenticationException(UserObject.class,"DatabaseMessages",
							       "auth.notFound");
      ae.setParameter(0,method_namespace);
      ae.setParameter(1,method);
      throw ae;

    } // end if

    // Retrieve the authentication data from the database.
    String[] stored_data = m_ops.getAuthenticationData(m_uid,m_ns_cache.namespaceNameToId(method_namespace),
						       method,source_data);
    if (stored_data==null)
    { // user has no data for this authentication method
      AuthenticationException ae = new AuthenticationException(UserObject.class,"DatabaseMessages",
							       "auth.noUserData");
      ae.setParameter(0,method_namespace);
      ae.setParameter(1,method);
      throw ae;

    } // end if

    // Now try the authentication.
    AuthenticationException ae = null;
    boolean rc = false;
    for (int i=0; !rc && (i<stored_data.length); i++)
    { // try the various authentication stored data
      try
      { // call authentication data...
	rc = auth.authenticate(stored_data[i],auth_data);

      } // end try
      catch (AuthenticationException e)
      { // save the exception
	ae = e;

      } // end catch

    } // end for

    if (rc)
      return true;
    if (ae!=null)
      throw ae;
    return false;

  } // end authenticate

  public void setAuthenticationData(DynamoUser caller, String method_namespace, String method,
				    String source_data, String auth_data)
      throws DatabaseException, AuthenticationException, DynamoSecurityException
  {
    testChangeOK(caller);
    if (m_anonymous)
      return;  // cannot change authentication data for anonymous user

    // Get the authenticator that handles these requests.
    Authenticator auth = m_auth_lookup.findAuthenticator(method_namespace,method);
    if (auth==null)
    { // the authenticator could not be found - bail out
      AuthenticationException ae = new AuthenticationException(UserObject.class,"DatabaseMessages",
							       "auth.notFound");
      ae.setParameter(0,method_namespace);
      ae.setParameter(1,method);
      throw ae;

    } // end if

    // Call down to set the authentication data.
    m_ops.putAuthenticationData(m_uid,m_ns_cache.namespaceNameToId(method_namespace),method,source_data,
				auth.processInputData(auth_data));

  } // end setAuthenticationData

  public void clearAuthenticationData(DynamoUser caller, String method_namespace, String method,
				      String source_data) throws DatabaseException, DynamoSecurityException
  {
    testChangeOK(caller);
    if (m_anonymous)
      return;  // cannot change authentication data for anonymous user

    // Call down to clear the authentication data.
    m_ops.clearAuthenticationData(m_uid,m_ns_cache.namespaceNameToId(method_namespace),method,source_data);

  } // end clearAuthenticationData

  public void clearAuthenticationData(DynamoUser caller, String method_namespace, String method)
      throws DatabaseException, DynamoSecurityException
  {
    testChangeOK(caller);
    if (m_anonymous)
      return;  // cannot change authentication data for anonymous user

    // Call down to clear the authentication data.
    m_ops.clearAuthenticationData(m_uid,m_ns_cache.namespaceNameToId(method_namespace),method,null);

  } // end clearAuthenticationData

  public java.util.Date getCreationDate()
  {
    return m_created;

  } // end getCreationDate

  public java.util.Date getLastAccessDate()
  {
    return m_last_accessed;

  } // end getLastAccessDate

  public synchronized void setLastAccessDate(DynamoUser caller, java.util.Date date)
      throws DatabaseException, DynamoSecurityException
  {
    testChangeOK(caller);
    m_ops.setLastAccessed(m_uid,date);
    m_last_accessed = date;

  } // end setLastAccessDate

  /*--------------------------------------------------------------------------------
   * External operations
   *--------------------------------------------------------------------------------
   */

  void updated(UserUpdateEvent evt)
  {
  } // end updated

} // end class UserObject
