package org.dbxml.xml.sax;

/*
 * 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: SAXEventGenerator.java,v 1.20 2001/09/06 19:13:18 kstaken Exp $
 */




import org.dbxml.xml.*;
import org.dbxml.xml.dom.*;
import org.dbxml.server.util.*;

import org.w3c.dom.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import org.xml.sax.ext.LexicalHandler;

import java.io.*;
import java.util.*;

/**
 * SAXEventGenerator
 */

public final class SAXEventGenerator implements XMLReader {
   private SymbolTable symbols = null;
   private byte[] data = null;
   private int pos = 0;
   private int len = 0;

   private List features = new ArrayList();
   private Map properties = new HashMap();
   private ContentHandler content = null;
   private LexicalHandler lexical = null;
   private CompressionHandler comp = null;
   private ErrorHandler errors = null;
   private EntityResolver entities = null;
   private DTDHandler dtd = null;

   private boolean interrupt = false;

   public SAXEventGenerator(SymbolTable symbols, byte[] data) {
      this.symbols = symbols;
      this.data = data;
      this.len = data.length;
   }

   public SAXEventGenerator(SymbolTable symbols, byte[] data, int pos, int len) {
      this.symbols = symbols;
      this.data = data;
      this.pos = pos;
      this.len = len;
   }

   public SAXEventGenerator(Document doc) {
      try {
         if ( doc instanceof CompressedDocument ) {
            doc = new DocumentImpl(doc);
            CompressedDocument cDoc = (CompressedDocument)doc;
            symbols = cDoc.getSymbols();
            data = cDoc.getDataBytes();
            pos = cDoc.getDataPos();
            len = cDoc.getDataLen();
         }
         else {
            symbols = new SymbolTable();
            data = DOMCompressor.Compress(doc, symbols);
            len = data.length;
         }
      }
      catch ( Exception e ) {
         // This shouldn't happen
         org.dbxml.Debug.printStackTrace(e);
      }
   }

   public boolean getFeature(String name) throws SAXNotRecognizedException, SAXNotSupportedException {
      return false;
   }

   public void setFeature(String name, boolean value) throws SAXNotRecognizedException, SAXNotSupportedException {
   }

   public Object getProperty(String name) throws SAXNotRecognizedException, SAXNotSupportedException {
      return properties.get(name);
   }

   public void setProperty(String name, Object value) throws SAXNotRecognizedException, SAXNotSupportedException {
      properties.put(name, value);

      if ( name.equals(CompressionHandler.HANDLER)
        && value instanceof CompressionHandler )
         comp = (CompressionHandler)value;

      if ( name.equals("http://xml.org/sax/properties/lexical-handler")
        && value instanceof LexicalHandler )
         lexical = (LexicalHandler)value;

   }

   public void setEntityResolver(EntityResolver resolver) {
      entities = resolver;
   }

   public EntityResolver getEntityResolver() {
      return entities;
   }

   public void setDTDHandler(DTDHandler handler) {
      dtd = handler;
   }

   public DTDHandler getDTDHandler() {
      return dtd;
   }

   public void setContentHandler(ContentHandler handler) {
      content = handler;
   }

   public ContentHandler getContentHandler() {
      return content;
   }

   public void setErrorHandler(ErrorHandler handler) {
      errors = handler;
   }

   public ErrorHandler getErrorHandler() {
      return errors;
   }

   public void parse(InputSource input) throws IOException, SAXException {
   }

   public void parse(String systemId) throws IOException, SAXException {
   }

   private final String getLocalName(String qname) {
      int idx = qname.indexOf(":");
      if ( idx != -1 )
         return qname.substring(idx+1);
      else
         return qname;
   }
   
   public boolean processContainer(boolean element, int pos, int len) throws IOException, SAXException {
      ByteArrayInput bis = new ByteArrayInput(data, pos, len);
      XMLCompressedInput in = new XMLCompressedInput(bis, symbols);
      String elemName = null;
      String localName = null;
      String nsURI = null;

      if ( element ) {
         in.readSignature();
         in.readContentSize();

         short elemSymbol = in.readShort();
         elemName = symbols.getName(elemSymbol);
         localName = getLocalName(elemName);
         nsURI = symbols.getNamespaceURI(elemSymbol);
         int attrCount = in.readAttributeCount();
         AttributesImpl attrs = new AttributesImpl();
         for ( int i = 0 ; i < attrCount; i++ ) {
            short symbol = in.readShort();
            short strLen = in.readShort();
            byte[] b = new byte[strLen];
            in.read(b);

            String attrName = symbols.getName(symbol);
            String attrURI = symbols.getNamespaceURI(symbol);
            String lclName = getLocalName(attrName);
            
            attrs.addAttribute(attrURI != null ? attrURI : "", lclName, attrName, "", new String(b));
         }
         if ( comp != null ) {
            comp.symbolID(elemSymbol);
            comp.dataLocation(pos, len);
         }
         content.startElement(nsURI !=null ? nsURI : "", localName, elemName, attrs);
      }
      else
         in.readInt();

      while ( !interrupt && bis.available() > 0 ) {
         pos = bis.getPos();
         byte signature = in.readSignature();
         len = in.readContentSize();
         if ( len == 0 )
            len = 1;

         NodeImpl impl = null;
         int type = in.getNodeType();


         switch ( type ) {

            case Node.ELEMENT_NODE:
               processContainer(true, pos, len);
               break;

            case Node.TEXT_NODE:
            case Node.PROCESSING_INSTRUCTION_NODE:
            case Node.CDATA_SECTION_NODE:
            case Node.COMMENT_NODE: {

               ByteArrayInput tbis = new ByteArrayInput(data, pos, len);
               XMLCompressedInput tin = new XMLCompressedInput(tbis, symbols);

               tin.readSignature(); // Skip The Signature
               if ( type == Node.TEXT_NODE )
                  tin.readContentSize();
               else
                  tin.readInt();

               byte[] buf = new byte[tbis.available()];
               tin.read(buf);

               String value = new String(buf);

               switch ( type ) {

                  case Node.TEXT_NODE:
                     char[] c = value.toCharArray();
                     content.characters(c, 0, c.length);
                     break;

                  case Node.PROCESSING_INSTRUCTION_NODE:
                     int i = value.indexOf(' ');
                     content.processingInstruction(value.substring(0, i), value.substring(i+1));
                     break;

                  case Node.CDATA_SECTION_NODE:
                     if (lexical != null) {
                        lexical.startCDATA();
                        char[] l = value.toCharArray();
                        content.characters(l, 0, l.length);
                        lexical.endCDATA();
                     }
                     break;
                  case Node.COMMENT_NODE:
                     if (lexical != null) {
                        char[] comm = value.toCharArray();
                        lexical.comment(comm, 0, comm.length);
                     }
                     break;
               }

               break;
            }

            case Node.ENTITY_REFERENCE_NODE:
               // TODO: This
               break;

            case Node.NOTATION_NODE:
               break;
         }

         bis.setPos(pos);
         bis.skip(len);
      }

      if ( element && !interrupt)
         content.endElement(nsURI != null ? nsURI : "", localName, elemName);

      return !interrupt;
   }

   public boolean processDocument() throws IOException, SAXException {
      if ( comp != null ) {
         comp.symbols(symbols);
         comp.dataBytes(data);
      }
      content.startDocument();
      boolean result = processContainer(false, pos, len);
      if ( result )
         content.endDocument();
      return result;
   }

   public boolean start() {
      try {
         return processDocument();
      }
      catch ( Exception e ) {
         org.dbxml.Debug.printStackTrace(e);
         return false;
      }
   }

   public void stop() {
      interrupt = true;
   }
}
