/**
 * 
 */
package org.ajax4jsf.config;

import java.io.StringReader;

import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

/**
 * @author asmirnov
 * 
 */
public abstract class StateHandler extends DefaultHandler {

	private final ContentHandler parentHandler;


	private int depth = 0;

	public StateHandler(ContentHandler parentHandler) {
		super();
		this.parentHandler = parentHandler;
	}

	@Override
	public void startElement(String uri, String localName, String name,
			Attributes attributes) throws SAXException {
		ContentHandler nextHandler = getNextHandler(uri, localName, attributes);
		if (null == nextHandler) {
			depth++;
		} else {
			getReader().setContentHandler(nextHandler);
		}
	}

	protected ContentHandler getNextHandler(String uri, String localName,
			Attributes attributes) {
		return null;
	}
	
	@Override
	public void endElement(String uri, String localName, String name)
			throws SAXException {
		if(depth-- == 0){
			if(null != parentHandler){
				getReader().setContentHandler(parentHandler);
			}
			endLastElement();
		}
	}

	protected void endLastElement() {
		// Do nothing		
	}
	
    @Override
    public InputSource resolveEntity(String publicId, String systemId) throws SAXException
    {
      // Do nothing, to avoid network requests to external DTD/Schema
      return new InputSource(new StringReader(""));
    }

	protected abstract XMLReader getReader(); 
}
