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: Database.java,v 1.4 2004/06/16 17:36:56 bradford Exp $
 */

import com.dbxml.db.common.adapters.DOMAdapter;
import com.dbxml.db.common.security.NoSecurityManager;
import com.dbxml.db.core.indexer.IndexManager;
import com.dbxml.db.core.query.QueryEngine;
import com.dbxml.db.core.security.SecurityManager;
import com.dbxml.db.core.security.User;
import com.dbxml.db.core.security.UserStack;
import com.dbxml.db.core.transaction.Transaction;
import com.dbxml.db.server.dbXML;
import com.dbxml.util.Configuration;
import com.dbxml.util.dbXMLException;
import com.dbxml.xml.dom.DOMHelper;
import com.dbxml.xml.dtsm.DTSMHelper;
import com.dbxml.xml.dtsm.DocumentTable;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 * The Database class, which is also a Collection class, serves as the
 * top level container for a dbXML database. It provides additional
 * capabilities such as providing access to the system collections,
 * symbol tables, and security manager. It is also the class that is
 * used to bootstrap the database and the collections therein.
 */

public class Database extends Collection {
   private static final String DBROOT = "dbroot";
   private static final String QUERYENGINE = "queryengine";
   private static final String SECURITY = "security";
   private static final String DATABASE = "database";
   private static final String COLKEY = "database.xml";
   private static final String NAME = "name";
   private static final String CLASS = "class";

   public static Database database;

   private boolean embedded;
   private Cache cache = new Cache();
   private List listeners = Collections.synchronizedList(new ArrayList());
   private SystemCollection sysCol;
   private QueryEngine engine = new QueryEngine(this);
   private SecurityManager security = new NoSecurityManager();
   private User magicUser;
   private UserStack userStack;

   protected Database(boolean embedded) throws DBException {
      if ( database != null )
         throw new DBException(FaultCodes.DBE_CANNOT_CREATE, "Only a single Database instance is allowed");

      database = this;
      this.embedded = embedded;
   }

   public Database() throws DBException {
      this(false);
   }

   public static Database getInstance() {
      return database;
   }

   public void setConfig(Configuration config) throws dbXMLException {
      magicUser = new User();
      userStack = new UserStack();

      try {
         userStack.pushCurrentUser(magicUser);

         IndexManager.setUserStack(userStack);
         IndexManager.setMagicUser(magicUser);

         this.config = config;

         name = config.getAttribute(NAME);
         setCanonicalName("/");

         String dbRoot = config.getAttribute(DBROOT);
         if ( dbRoot != null && dbRoot.length() > 0 )
            setCollectionRoot(new File(dbRoot));
         else {
            File homeDir = new File(System.getProperty(dbXML.PROP_DBXML_HOME));
            setCollectionRoot(new File(homeDir, "db"));
         }

         try {
            Configuration queryCfg = config.getChild(QUERYENGINE);
            if ( queryCfg != null )
               engine.setConfig(queryCfg);
         }
         catch ( Exception e ) {
            e.printStackTrace(System.err);
            throw new dbXMLException("Couldn't initialize Query Engine", e);
         }

         try {
            sysCol = new SystemCollection(this, magicUser, userStack);
            try {
               sysCol.init();
            }
            catch ( dbXMLException e ) {
               e.printStackTrace(System.err);
            }
            collections.put(sysCol.getName(), sysCol);
         }
         catch ( Exception e ) {
            e.printStackTrace(System.err);
            throw new dbXMLException("Couldn't initialize System Collection", e);
         }

         Transaction tx = new Transaction();
         try {
            // Bootstrap from the database itself...  This is accomplished
            // by intercepting the setConfig call and using a Configuration
            // retrieved from the database instead of the standard config
            Collection col = sysCol.getCollection(SystemCollection.CONFIGS);
            DOMAdapter domAdapter = new DOMAdapter(col);
            Document colDoc = domAdapter.getDocument(tx, COLKEY);

            if ( colDoc == null ) {
               colDoc = DOMHelper.newDocument();
               Element root = colDoc.createElement(DATABASE);
               root.setAttribute(NAME, name);
               colDoc.appendChild(root);

               domAdapter.setDocument(tx, COLKEY, colDoc);
            }

            super.setConfig(new Configuration(colDoc));
         }
         catch ( Throwable e ) {
            tx.cancel();
            e.printStackTrace(System.err);
            throw new dbXMLException("Couldn't bootstrap Database", e);
         }
         finally {
            if ( tx.getStatus() == Transaction.ACTIVE )
               tx.commit();
         }

         try {
            Configuration securityCfg = config.getChild(SECURITY);
            if ( securityCfg != null ) {
               String className = securityCfg.getAttribute(CLASS);
               security = (SecurityManager)ClassResolver.get(className).newInstance();
               security.setDatabase(this);
               security.setMagicUser(magicUser);
               security.setUserStack(userStack);
               security.setConfig(securityCfg);
            }
         }
         catch ( Exception e ) {
            e.printStackTrace(System.err);
            throw new dbXMLException("Couldn't initialize Security Manager", e);
         }
      }
      finally {
         userStack.popCurrentUser();
      }
   }

   public boolean isDatabaseEmbedded() {
      return embedded;
   }

   public void addDatabaseEventListener(DatabaseEventListener listener) {
      if ( !listeners.contains(listener) )
         listeners.add(listener);
   }

   public void removeDatabaseEventListener(DatabaseEventListener listener) {
      if ( listeners.contains(listener) )
         listeners.remove(listener);
   }

   void fireCreateCollection(Collection col) {
      Iterator iter = listeners.iterator();
      while ( iter.hasNext() ) {
         DatabaseEventListener listener = (DatabaseEventListener)iter.next();
         listener.createCollection(col);
      }
   }

   void fireDropCollection(Collection col) {
      Iterator iter = listeners.iterator();
      while ( iter.hasNext() ) {
         DatabaseEventListener listener = (DatabaseEventListener)iter.next();
         listener.dropCollection(col);
      }
   }

   public SystemCollection getSystemCollection() {
      return sysCol;
   }

   public Database getDatabase() {
      return this;
   }

   /**
    * flushConfig ensures that the Collection configuration has been
    * properly flushed to disk after a modification.
    */
   public void flushConfig() throws DBException {
      Transaction tx = new Transaction();
      try {
         userStack.pushCurrentUser(magicUser);

         Document d = config.getElement().getOwnerDocument();
         Collection col = sysCol.getCollection(SystemCollection.CONFIGS);
         DocumentTable dt = DTSMHelper.documentToTable(d, col.getSymbols());
         col.setDocument(tx, COLKEY, dt);
      }
      catch ( Exception e ) {
         tx.cancel();
         System.err.println("Error Writing Configuration '" + name + "'");
      }
      finally {
         userStack.popCurrentUser();

         if ( tx.getStatus() == Transaction.ACTIVE )
            tx.commit();
      }
   }

   /**
    * getCache returns the Database-level Cache.
    *
    * @return The Cache
    */
   public Cache getCache() {
      return cache;
   }

   /**
    * getQueryEngine returns a reference to the Database's
    * QueryEngine.
    *
    * @return The QueryEngine instance
    */
   public QueryEngine getQueryEngine() {
      return engine;
   }

   /**
    * getSecurityManager returns a reference to the Database's
    * SecurityManager.
    *
    * @return The SecurityManager instance
    */
   public SecurityManager getSecurityManager() {
      return security;
   }

   public void dispose() {
      try {
         flushConfig();
      }
      catch ( DBException e ) {
         /** @todo What do we do here? */
      }
      super.dispose();
      database = null;
   }
}


