package com.dbxml.db.common.xupdate;

/*
 * 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: XUpdateImpl.java,v 1.2 2004/02/12 00:17:56 bradford Exp $
 */

import com.dbxml.db.common.adapters.DOMAdapter;
import com.dbxml.db.common.xpath.XPathQueryResolver;
import com.dbxml.db.core.data.Key;
import com.dbxml.db.core.query.ResultSet;
import com.dbxml.db.core.transaction.Transaction;
import java.util.Enumeration;
import java.util.Hashtable;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xmldb.xupdate.lexus.XUpdateQueryImpl;
import org.xmldb.xupdate.lexus.commands.CommandConstants;
import org.xmldb.xupdate.lexus.commands.CommandObject;
import org.xmldb.xupdate.lexus.commands.DefaultCommand;

/**
 * Provides Collection and document based XUpdate capabilities.
 *
 * For more detail about XUpdate look at the
 * <a href="http://www.xmldb.org/xupdate/xupdate-wd.html">XUpdate Working Draft</a>.
 */
public class XUpdateImpl extends XUpdateQueryImpl {
   private int modified;

   /**
    * Execute the XUpdate commands against a document.
    */
   public void execute(Node contextNode) throws Exception {
      CommandObject currentCommand = new DefaultCommand(contextNode);
      Enumeration commands = _query[0].elements();
      Enumeration attributes = _query[1].elements();
      Enumeration characters = _query[2].elements();

      while ( commands.hasMoreElements() ) {
         int id = ((Integer)commands.nextElement()).intValue();

         if ( id == CommandConstants.ATTRIBUTES ) {
            currentCommand.submitAttributes((Hashtable)attributes.nextElement());
         }
         else if ( id == CommandConstants.CHARACTERS ) {
            currentCommand.submitCharacters((String)characters.nextElement());
         }
         else if ( id > 0 ) {
            if ( !currentCommand.submitInstruction(id) ) {
               _commands.setContextNode(contextNode);
               currentCommand = _commands.commandForID(id);
               if ( currentCommand == null ) {
                  throw new Exception("operation can not have any XUpdate-instruction !");
               }
               currentCommand.reset();
            }
         }
         else {
            if ( !currentCommand.executeInstruction() ) {
               contextNode = currentCommand.execute();
               currentCommand = new DefaultCommand(contextNode);
            }
         }
      }
   }

   /**
    * getModified returns the number of modified Documents.
    *
    * @return Modified document count
    */
   public int getModified() {
      return modified;
   }

   /**
    * Execute the set of XUpdate commands against a collection (in the form
	 * of a DOMAdapter).
    *
    * @param contextNode Description of Parameter
    * @exception Exception Description of Exception
    */
   public void execute(Transaction tx, DOMAdapter domAdapter) throws Exception {

      int attribIndex = 0;
      for ( int i = 0; i < _query[0].size(); i++ ) {
         int cmdID = ((Integer)_query[0].elementAt(i)).intValue();

         if ( cmdID == CommandConstants.ATTRIBUTES ) {
            Hashtable attribs = (Hashtable)_query[1].elementAt(attribIndex);
            attribIndex++;
            String selector = (String)attribs.get("select");

            // If we found an XPath selector we need to execute the commands.
            if ( selector != null ) {
               ResultSet rs = domAdapter.queryCollection(tx, XPathQueryResolver.STYLE_XPATH, selector, null);
               Key lastKey = null;
               while ( rs != null && rs.next() ) {
                  Key key = rs.getResultKey();
                  if ( lastKey != null && (key == lastKey || key.equals(lastKey)) )
                     continue;

						Document doc = domAdapter.getDocument(tx, key);
						
						if ( doc == null )
							continue;
						
                  Node ctxNode = doc.getDocumentElement();
                  execute(ctxNode);
						
                  // If there's still a Document Element, then update.
                  // Otherwise, XUpdate wanted to delete the Document
                  if ( doc.getDocumentElement() != null )
							domAdapter.setDocument(tx, key, doc);
                  else
                     domAdapter.remove(tx, key);

                  modified++;
               }
            }
         }
      }
   }
}

