// copyright => http://www.jxml.com/mdsax/License.txt

package com.jxml.quick;
import org.xml.sax.*;
import java.util.*;
import java.io.*;

public class QConvert 
    implements DocumentHandler		    
{
    public static final String ATTRIBUTES="_attributes";
    public QContext context;
    private ArrayList atts=new ArrayList();
    private StringBuffer text=new StringBuffer();
    private boolean ignoreText=false;

    public QConvert()
    {
	context=new com.jxml.quick.engine.QContextImpl();
    }

    public QConvert(QContext context)
    {
	this.context=context;
    }

    public void setDocumentLocator(Locator locator)
    {
	context.locator=locator;
    }

    public void startDocument()
	throws SAXException
    {
//	try
//	    {
		context.startDocument();
//	    } 
//	catch (RuntimeException re)
//	    {
//re.printStackTrace();
//		context.throwPE(re);
//	    }
    }

    public void endDocument()
	throws SAXException
    {
//	try
//	    {
		context.endDocument();
//	    } 
//	catch (RuntimeException re)
//	    {
//re.printStackTrace();
//		context.throwPE(re);
//	    }
    }

    public void startElement(String name, AttributeList attList)
	throws SAXException
    {
//	try
//	    {
		context.startElement(name);
		int len=attList.getLength();
		context.startElement(ATTRIBUTES);
		int i;
		Att att;
		for (i=0;i<len;++i)
		    {
			if (atts.size()==i)
			    atts.add(new Att());
			att=(Att)atts.get(i);
			att.name=attList.getName(i);
			att.value=attList.getValue(i);
		    }
		for (i=0;i<len;++i)
		    {
			att=(Att)atts.get(i);
			int k;
			for (k=i+1;k<len;++k)
			    {
				Att a=(Att)atts.get(k);
				if (att.name.compareTo(a.name)>0)
				    {
					atts.set(k,att);
					att=a;
				    }
			    }
			atts.set(i,att);
			context.startElement(att.name);
			context.endElement(att.name,att.value,false);
		    }
		context.endElement(ATTRIBUTES,"",false);
		text.setLength(0);
		ignoreText=false;
//	    } 
//	catch (RuntimeException re)
//	    {
//re.printStackTrace();
//		context.throwPE(re);
//	    }
    }

    public void endElement(String name)
	throws SAXException
    {
//	try
//	    {
		if (ignoreText)
		    context.endElement(name,"",false);
		else
		    context.endElement(name,text.toString(),false);
		ignoreText=true;
//	    } 
//	catch (RuntimeException re)
//	    {
//re.printStackTrace();
//		context.throwPE(re);
//	    }
    }

    public void ignorableWhitespace(
				    char[] chars,
				    int offset,
				    int len)
	throws SAXException
    {
	characters(chars,offset,len);
    }

    public void characters(
			   char[] chars,
			   int offset,
			   int len)
	throws SAXException
    {
	if (ignoreText)
	    return;
	text.append(chars,offset,len);
    }

    public void processingInstruction(
				      String target, 
				      String data)
	throws SAXException
    {
    }

    public class Att
    {
	public String name;
	public String value;
    }
}
