/*
 * 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.event.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.security.SecurityReferenceMonitor;
import com.silverwrist.dynamo.util.*;

class GlobalPropertiesObject implements SecureObjectStore
{
  /*--------------------------------------------------------------------------------
   * Attributes
   *--------------------------------------------------------------------------------
   */

  private GlobalPropertiesOps m_ops;                // operations object
  private NamespaceCache m_ns_cache;                // namespace cache
  private SecurityReferenceMonitor m_srm;           // security reference monitor
  private PostDynamicUpdate m_post;                 // where we post dynamic events
  private ReferenceMap m_properties;                // cached property values

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

  GlobalPropertiesObject(DBConnectionPool pool, NamespaceCache ns_cache, SecurityReferenceMonitor srm,
			 PostDynamicUpdate post) throws ConfigException
  {
    m_ops = GlobalPropertiesOps.get(pool);
    m_ns_cache = ns_cache;
    m_srm = srm;
    m_post = post;
    m_properties = new ReferenceMap(ReferenceMap.HARD,ReferenceMap.SOFT);

  } // end constructor

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

  private final void testPermission(DynamoUser caller, String perm_namespace, String perm_name,
				    String fail_message) throws DatabaseException, DynamoSecurityException
  {
    if (caller.equals(m_srm.getAdminUser()))
      return;  // Administrator can do anything
    if (m_srm.getGlobalAcl().testPermission(caller,perm_namespace,perm_name))
      return;  // we have the right permission in the ACL
    throw new DynamoSecurityException(GroupObject.class,"DatabaseMessages",fail_message);

  } // end testPermission

  /*--------------------------------------------------------------------------------
   * 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)
  {
    try
    { // convert the namespace name to an ID here
      PropertyKey key = new PropertyKey(m_ns_cache.namespaceNameToId(namespace),name);
      Object rc = null;
      synchronized (this)
      { // 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(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
  {
    testPermission(caller,namespace,"set.property","sec.setGlobalProperty");
    Object rc = null;
    // convert the namespace name to an ID here
    PropertyKey key = new PropertyKey(m_ns_cache.namespaceNameToId(namespace),name);
    synchronized (this)
    { // start by setting the database value
      rc = m_ops.setProperty(key,value);
      
      // and cache it, too
      m_properties.put(key,value);

    } // end synchronized block

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

  } // end setObject

  public Object removeObject(DynamoUser caller, String namespace, String name)
      throws DatabaseException, DynamoSecurityException
  {
    testPermission(caller,namespace,"remove.property","sec.removeGlobalProperty");
    Object rc = null;
    // convert the namespace name to an ID here
    PropertyKey key = new PropertyKey(m_ns_cache.namespaceNameToId(namespace),name);
    synchronized (this)
    { // start by killing the database value
      rc = m_ops.removeProperty(key);

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

    } // end synchronized block

    m_post.postUpdate(new GlobalPropertyUpdateEvent(this,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();

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

  } // end getNamespaces

  public Collection getNamesForNamespace(String namespace) throws DatabaseException
  {
    // call through to the database to get the data for this namespace
    int nsid = m_ns_cache.namespaceNameToId(namespace);
    Map data = m_ops.getAllProperties(nsid);

    // we both create the return value and cache the data values
    ArrayList rc = new ArrayList(data.size());
    synchronized (this)
    { // 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

} // end class GlobalPropertiesObject
