package org.dbxml.core.xupdate;

/*
 * dbXML License, Version 1.0
 *
 *
 * Copyright (c) 1999-2001 The dbXML Group, L.L.C.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by
 *        The dbXML Group (http://www.dbxml.com/)."
 *    Alternately, this acknowledgment may appear in the software
 *    itself, if and wherever such third-party acknowledgments normally
 *    appear.
 *
 * 4. The names "dbXML" and "The dbXML Group" must not be used to
 *    endorse or promote products derived from this software without
 *    prior written permission. For written permission, please contact
 *    info@dbxml.com.
 *
 * 5. Products derived from this software may not be called "dbXML",
 *    nor may "dbXML" appear in their name, without prior written
 *    permission of The dbXML Group.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE DBXML GROUP OR ITS CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * $Id: XUpdateImpl.java,v 1.11 2001/09/06 18:34:54 kstaken Exp $
 */

import org.dbxml.core.Collection;
import org.dbxml.core.data.*;
import org.dbxml.xml.dom.*;
import org.dbxml.xml.*;

import org.infozone.lexus.commands.*;
import org.infozone.lexus.*;

import java.util.*;

import org.w3c.dom.*;

/**
 * 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 {
   protected int nodesModified = 0;
   
   /**
    * 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();
      Node origNode = contextNode;

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

         if ( id == _commands.ATTRIBUTES ) {
            currentCommand.submitAttributes((Hashtable) attributes.nextElement());
         }
         else if ( id == _commands.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);
            }
         }
      }

      if ( origNode instanceof CompressedNode ) {
         CompressedNode cn = (CompressedNode)origNode;
         if ( cn.isDirty() )
            nodesModified++;
      }
   }

   /**
    * Execute the set of XUpdate commands against a collection.
    *
    * @param contextNode Description of Parameter
    * @exception Exception Description of Exception
    */
   public void execute(Collection col) throws Exception {

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

         if ( cmdID == _commands.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) {
               NodeSet ns = col.queryCollection("XPath", selector, null);
               Document lastDoc = null;
               while (ns != null && ns.hasMoreNodes()) {
                  DBNode node = (DBNode)ns.getNextNode();
                  Document doc = node.getOwnerDocument();
                  
                  if ( doc == lastDoc )
                     continue; // We only have to process it once
                  else
                     lastDoc = doc;
                  
                  NodeSource source = node.getSource();

                  Node contextNode = doc.getDocumentElement();
                  try {
                     execute(contextNode);
                  } catch (Exception e) {
                     if (! e.getMessage().equals("no nodes selected !")) {
                        throw e;
                     }
                  }

                  col.setDocument(source.getKey(), doc);
               }
            }
         }
      }
   }
   
   public int getModifiedCount() {
      return nodesModified;
   }
}

