package name.panitz.xml;

import name.panitz.crempel.util.FromTo;
import name.panitz.saxtest.*;
import org.xml.sax.helpers.DefaultHandler;
import java.util.*;
import org.xml.sax.*;

public class SaxToXML extends DefaultHandler{
  Stack<List<XML>> children = new Stack<List<XML>>();
  Stack<List<Attribute>> attributes = new Stack<List<Attribute>>();
  public SaxToXML(){children.push(new ArrayList<XML>());}

  public void startElement
   (String uri, String localName, String qName, Attributes attrs)
                throws SAXException {
    children.push(new ArrayList<XML>());
    ArrayList<Attribute> myAttrs = new ArrayList<Attribute>();
    for (int i:new FromTo(0,attrs.getLength()-1))
      myAttrs.add(
         new Attribute
          (new Name(attrs.getLocalName(i)
                   ,attrs.getQName(i)
                   ,attrs.getURI(i))
          ,attrs.getValue(i)));
    attributes.push(myAttrs);
  }

  public void endElement
    (String uri, String localName, String qName)
                throws SAXException {
    List<XML> chds = children.pop();
    children.peek().add(new Element(new Name(localName,qName,uri)
                                   ,attributes.pop()
                                   ,chds));
  }

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

  }

  public void characters(char[] ch,int start,int length)
                throws SAXException {
    String text = new String(ch,start,length);
    children.peek().add(
     new Text(text.replace("<","&lt;")
                  .replace(">","&gt;")
                  .replace("&","&amp;")
                  .replace("\"","&quot;")
                  .replace("'","&apos;")
    ));

  }

  public static void main(String [] args) throws Exception{
    SaxToXML toXML = new SaxToXML();
    SaxParse.parse(new java.io.File(args[0]),toXML);
    XML doc = toXML.children.pop().get(0);
    System.out.println(doc.visit(new ToHTML()));
  }
}