/*
 * 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 com.silverwrist.util.*;
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 GlobalBlocksObject implements SecureObjectStore
{
  /*--------------------------------------------------------------------------------
   * Attributes
   *--------------------------------------------------------------------------------
   */

  private GlobalBlocksOps 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 HardSoftCache m_cache;                    // our cache

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

  GlobalBlocksObject(DBConnectionPool pool, NamespaceCache ns_cache, SecurityReferenceMonitor srm,
		     PostDynamicUpdate post, int hard_limit, int soft_limit) throws ConfigException
  {
    m_ops = GlobalBlocksOps.get(pool);
    m_ns_cache = ns_cache;
    m_srm = srm;
    m_post = post;
    m_cache = new HardSoftCache(hard_limit,soft_limit);

  } // 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 block cache
	rc = m_cache.get(key);
	if (rc==null)
	{ // no use - need to try the database
	  rc = m_ops.getBlock(key);
	  if (rc!=null)
	    m_cache.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.block","sec.setGlobalBlock");
    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.putBlock(key,value.toString());

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

    } // end synchronized block

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

  } // end setObject

  public Object removeObject(DynamoUser caller, String namespace, String name)
      throws DatabaseException, DynamoSecurityException
  {
    testPermission(caller,namespace,"remove.block","sec.removeGlobalBlock");
    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.removeBlock(key);

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

    } // end synchronized block

    m_post.postUpdate(new GlobalBlockUpdateEvent(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.getBlockNamespaceIDs();

    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, then get names
    return m_ops.getAllBlockNames(m_ns_cache.namespaceNameToId(namespace));
    // N.B.: we do not retrieve all blocks and cache them the way we do with properties because
    // blocks can potentially be HUGE, and our cache size is limited at best

  } // end getNamesForNamespace

} // end class GlobalBlocksObject
