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: SystemCollection.java,v 1.4 2004/08/22 04:18:42 bradford Exp $
 */

import com.dbxml.db.common.adapters.XMLSerializableAdapter;
import com.dbxml.db.core.security.User;
import com.dbxml.db.core.security.UserStack;
import com.dbxml.db.core.transaction.Transaction;
import com.dbxml.util.Configuration;
import com.dbxml.xml.SymbolTable;
import com.dbxml.xml.dom.DOMHelper;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

/**
 * SystemCollection represents the System Collection.  Beyond
 * standard Collection operations, this class will provide facilities
 * for Schema and SymbolTable management among other things.
 */

public final class SystemCollection extends Collection {
   private static final String SYSCOL_XML = "SystemCollection.xml";

   public static final String SYSCOL = "system";

   public static final String SYMBOLS = "SysSymbols";
   public static final String METADATA = "SysMetaData";
   public static final String OBJECTS = "SysObjects";
   public static final String CONFIGS = "SysConfig";
   public static final String SCHEMAS = "SysSchemas";
   public static final String USERS = "SysUsers";
   public static final String USERPROPERTIES = "SysUserProperties";
   public static final String ROLES = "SysRoles";
   public static final String ACCESS = "SysAccess";

   private UserStack userStack;
   private User magicUser;

   private XMLSerializableAdapter symCol;

   SystemCollection(Database db, User magicUser, UserStack userStack) {
      super(db);
      this.magicUser = magicUser;
      this.userStack = userStack;
   }

   void init() throws DBException {
      try {
         // Bootstrap the System Collection from Resource
         InputStream is = getClass().getResourceAsStream(SYSCOL_XML);
         InputStreamReader isr = new InputStreamReader(is, "UTF8");
         BufferedReader br = new BufferedReader(isr, 4096);

         Document sysDoc = DOMHelper.parse(new InputSource(br));
         Configuration sysCfg = new Configuration(sysDoc);
         setConfig(sysCfg);
         br.close();
      }
      catch ( Exception e ) {
         System.err.println("FATAL ERROR: Generating System Collection '" + SYSCOL + "'");
         e.printStackTrace(System.err);
         System.exit(1);
      }
   }

   /**
    * loadSymbols retrieves the SymbolTable for the specified Collection.
    *
    * @param collection The Collection whose SymbolTable is required
    * @return The requested SymbolTable
    * @throws DBException If a Database Exception occurs
    */
   public SymbolTable loadSymbols(Collection collection) throws DBException {
      Transaction tx = new Transaction();
      try {
         userStack.pushCurrentUser(magicUser);

         XMLSerializableAdapter symCol = getSymbolsCollection();
         String colName = collection.getCanonicalName();
         SymbolTable symbols = (SymbolTable)symCol.getObject(tx, colName);
         if ( symbols == null ) {
            symbols = new SymbolTable();
            saveSymbols(collection, symbols);
         }

         return symbols;
      }
      catch ( DBException e ) {
         tx.cancel();
         e.printStackTrace(System.err);
         throw e;
      }
      finally {
         userStack.popCurrentUser();

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

   /**
    * saveSymbols save the SymbolTable for the specified Collection.
    *
    * @param collection The Collection that owns the SymbolTable
    * @param symbols The SymbolTable
    * @throws DBException If a Database Exception occurs
    */
   public void saveSymbols(Collection collection, SymbolTable symbols) throws DBException {
      Transaction tx = new Transaction();
      try {
         userStack.pushCurrentUser(magicUser);

         if ( symbols != null ) {
            XMLSerializableAdapter symCol = getSymbolsCollection();
            String colName = collection.getCanonicalName();
            symCol.setObject(tx, colName, symbols);
            symbols.setDirty(false);
         }
      }
      catch ( DBException e ) {
         tx.cancel();
         e.printStackTrace(System.err);
         throw e;
      }
      finally {
         userStack.popCurrentUser();

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

   private XMLSerializableAdapter getSymbolsCollection()throws DBException {
      if ( symCol == null ) {
         Collection col = getCollection(SYMBOLS);
         symCol = new XMLSerializableAdapter(col);
      }
      return symCol;
   }
}
