package com.dbxml.db.core;

/*
 * dbXML - Native XML Database
 * Copyright (C) 1999-2004  The dbXML Group, L.L.C.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * $Id: CollectionManager.java,v 1.3 2004/02/12 00:17:56 bradford Exp $
 */

import com.dbxml.db.core.security.Access;
import com.dbxml.db.core.security.SecurityException;
import com.dbxml.util.Configurable;
import com.dbxml.util.Configuration;
import com.dbxml.util.ConfigurationCallback;
import com.dbxml.util.dbXMLException;
import java.util.Collections;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TreeMap;

/**
 * CollectionManager is the base class for Collection, and as a result
 * Database as well.
 */

public abstract class CollectionManager implements Configurable {
   private static final String COLLECTIONS = "collections";
   private static final String COLLECTION = "collection";
   private static final String NAME = "name";

   private static final String[] EmptyStrings = new String[0];

   protected Map collections = Collections.synchronizedMap(new TreeMap()); // Collection

   protected Configuration config;

   protected CollectionManager() {
   }

   public void setConfig(Configuration config) throws dbXMLException {
      this.config = config;

      Configuration colConfig = config.getChild(COLLECTIONS);
      if ( colConfig != null ) {
         colConfig.processChildren(COLLECTION,
            new ConfigurationCallback() {
               public void process(Configuration cfg) throws dbXMLException {
                  Collection col = new Collection((Collection)CollectionManager.this);
                  col.setConfig(cfg);
                  collections.put(col.getName(), col);
               }
            });
      }
   }

   public Configuration getConfig() {
      return config;
   }

   private void checkAccess(int permissions) throws SecurityException {
      getDatabase().getSecurityManager().access(getCanonicalName(), permissions);
   }

   /**
    * getName returns the name for this Object.
    * <br>
    * ex: ocs
    *
    * @return The name
    */
   public abstract String getName();

   /**
    * getCanonicalName returns the canonical name for this Object.
    * <br>
    * ex: /local/test/ocs
    *
    * @return The canonical name
    */
   public abstract String getCanonicalName();

   /**
    * getSystemCollection returns the System Collection.
    *
    * @return The System Collection
    * @throws DBException If a Database Exception occurs*
    */
   public abstract SystemCollection getSystemCollection() throws DBException;

   /**
    * getDatabase retrieves the Database that is associated with this
    * CollectionManager.
    *
    * @return The Database
    */
   public abstract Database getDatabase();

   /**
    * getCollection retrieves a Collection by name.
    *
    * @param path The Collection path
    * @return The Collection
    * @throws DBException If a Database Exception occurs
    */
   public Collection getCollection(String path) throws DBException {
      Collection col = null;

      if ( path.indexOf("/") != -1 ) {
         CollectionManager cm = this;
         StringTokenizer st = new StringTokenizer(path, "/");
         while ( cm != null && st.hasMoreTokens() ) {
            path = st.nextToken();
            cm = (CollectionManager)cm.collections.get(path);
         }
         col = (Collection)cm;
      }
      else
         col = (Collection)collections.get(path);

      if ( col != null )
         return col;
      else
         throw new DBException(FaultCodes.COL_COLLECTION_NOT_FOUND, "Collection '"+path+"' not found");
   }

   /**
    * listCollections retrieves a list of Collections as an array of
    * Strings.
    *
    * @return The Collection list
    * @throws DBException If a Database Exception occurs
    */
   public final String[] listCollections() throws DBException {
      return (String[])collections.keySet().toArray(EmptyStrings);
   }

   /**
    * dropCollection physically removes the specified Collection and any
    * associated system resources that the Collection uses.
    *
    * @param collection The Collection to drop
    * @return Whether or not the Collection was dropped
    * @throws DBException If a Database Exception occurs
    */
   public boolean dropCollection(Collection collection) throws DBException {
      if ( collection == null )
         throw new DBException(FaultCodes.COL_COLLECTION_NOT_FOUND, "Collection Value Null");

      checkAccess(Access.CREATE);

      Collection cm = collection.getParentCollection();

      if ( cm == null )
         throw new DBException(FaultCodes.DBE_CANNOT_DROP, "You Cannot Drop The Database");

      if ( cm != this )
         return cm.dropCollection(collection);
      else {
         final String name = collection.getName();
         boolean dropped = collection.drop();
         if ( dropped ) {
            collections.remove(name);
            Configuration colConfig = config.getChild(COLLECTIONS);
            colConfig.processChildren(COLLECTION,
               new ConfigurationCallback() {
                  public void process(Configuration cfg) {
                     try {
                        if ( cfg.getAttribute(NAME).equals(name) )
                           cfg.delete();
                     }
                     catch ( Exception e ) {
                        e.printStackTrace(System.err);
                     }
                  }
               });
         }
         getDatabase().fireDropCollection(collection);
         return dropped;
      }
   }

   /**
    * createCollection creates a new Collection object and any associated
    * system resources that the Collection will need.
    *
    * @param path The relative path of the Collection
    * @param cfg The Collection's configuration
    * @return The newly created Collection
    * @throws DBException If a Database Exception occurs
    */
   public Collection createCollection(String path, Configuration cfg) throws DBException {
      checkAccess(Access.CREATE);

      if ( path.indexOf("/") != -1 ) {
         CollectionManager cm = this;
         StringTokenizer st = new StringTokenizer(path, "/");
         while ( cm != null && st.hasMoreTokens() ) {
            path = st.nextToken().trim();
            if ( path.length() == 0 )
               continue;
            if ( st.hasMoreTokens() )
               cm = (CollectionManager)cm.collections.get(path);
            else
               return cm.createCollection(path, cfg);
         }
         throw new DBException(FaultCodes.COL_COLLECTION_NOT_FOUND, "Parent Collection '" + path + "' doesn't exist");
      }

      Collection collection = new Collection((Collection)this);

      try {
         // Do a name check to see if all is well
         String n = cfg.getAttribute(NAME);
         if ( n == null || n.trim().equals("") )
            throw new DBException(FaultCodes.COL_CANNOT_CREATE, "No name specified");

         boolean found = false;
         try {
            found = getCollection(n) != null;
         }
         catch ( DBException e ) {
         }

         if ( found )
            throw new DBException(FaultCodes.COL_DUPLICATE_COLLECTION, "Duplicate Collection '" + n + "'");

         Configuration colConfig = this.config.getChild(COLLECTIONS, true);
         colConfig.add(cfg);

         collection.setConfig(cfg);
         collections.put(n, collection);

         getDatabase().fireCreateCollection(collection);
      }
      catch ( DBException d ) {
         throw d;
      }
      catch ( Exception e ) {
         throw new DBException(FaultCodes.COL_CANNOT_CREATE, "Error Creating Collection '" + path + "'", e);
      }
      return collection;
   }
}


