/* $Id: XmlObjMapper.java,v 1.5 2006/06/21 11:13:03 erk Exp $
 * -----------------------------------------------------------------------
 * 
 * TSP Library - core components for a generic Transport Sampling Protocol.
 * 
 * Copyright (c) 2002 Yves DUFRENNE, Stephane GALLES, Eric NOULARD and Robert PAGNOT 
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 * 
 * -----------------------------------------------------------------------
 * 
 * Project    : TSP
 * SubProject : jTSP
 * Maintainer : tsp@astrium-space.com
 * Component  : 
 * 
 * -----------------------------------------------------------------------
 * 
 * Purpose   : 
 * 
 * -----------------------------------------------------------------------
 */


package tsp.util.xml.objmapper;


import java.io.CharArrayWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.ParserConfigurationException;

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

public class XmlObjMapper extends DefaultHandler {

	private final static String CLASSPATH_URL_PREFIX = "classpath:";
	
	private final static int XML_FILE_DEPTH = 10;
		
	private LinkedList positionRecorder = new LinkedList();

	private CharArrayWriter[] contents = new CharArrayWriter[XML_FILE_DEPTH];

	private XMLReader xmlReader;

	private PositionIdle positionIdle = new PositionIdle();
	
	private int nlevel=-1;

	public XmlObjMapper() throws ParserConfigurationException, SAXException {

		SAXParserFactory saxFactory = SAXParserFactory.newInstance();
		saxFactory.setNamespaceAware(true);		

		xmlReader = saxFactory.newSAXParser().getXMLReader();
		positionRecorder.addLast(new PositionActive());

	}

	public PositionNode getRoot() {
		return (PositionNode) positionRecorder.getFirst();
	}

	public void startElement(String namespaceURI, String localName,
			String qName, Attributes attr) throws SAXException {
		
		nlevel+=1;
		contents[nlevel] = new CharArrayWriter();
	    contents[nlevel].reset();
		Position currentPos = (Position) positionRecorder.getLast();
		currentPos.startElement(localName, attr);

	}

	public void endElement(String namespaceURI, String localName, String qName)
			throws SAXException {
		Position currentPos = (Position) positionRecorder.getLast();
		currentPos.endElement(localName);
		
	}

	public void characters(char[] ch, int start, int length)
			throws SAXException {
		contents[nlevel].write(ch, start, length);
	
	}

	class PositionActive implements Position, PositionNode {

		PositionAction action;

		private Map configuredPositions = new HashMap();

		public PositionActive(PositionAction action) {
			this.action = action;
		}

		public PositionActive() {
			action = new PositionAction() {
				public void start(Attributes attr) throws SAXException {
				}

				public void end(String contents) {
				}
			};
		}

		public void addNode(String tagName, PositionAction handler) {
			Object obj = configuredPositions.put(tagName, new PositionActive(handler));
			if (obj != null) {
				throw new IllegalStateException("element " + tagName
						+ "already mapped");
			}
		}

		public PositionNode getNode(String tagName) {
			PositionActive obj = (PositionActive) configuredPositions.get(tagName);
			if (obj == null) {
				throw new IllegalStateException("element " + tagName
						+ " not already mapped");
			}
			return obj;
		}

		public void startElement(String localName, Attributes attr)
				throws SAXException {


			PositionActive currentPos = (PositionActive) configuredPositions.get(localName);
			if (currentPos == null) {
				positionRecorder.addLast(positionIdle);
			} else {
				currentPos.onStart(attr);
				positionRecorder.addLast(currentPos);
			}
		}

		public void endElement(String localName) throws SAXException {
			
			onEnd(contents[nlevel].toString());
			nlevel-=1;
			
			positionRecorder.removeLast();
		}

		public final void onStart(Attributes attr) throws SAXException {
			action.start(attr);
		}

		public final void onEnd(String contents) throws SAXException {
			action.end(contents);
		}

	}

	class PositionIdle implements Position {

		public void startElement(String localName, Attributes attr) {
			positionRecorder.addLast(this);
            // Uncomment this if you want to see ignored TAG
            // System.out.println("Tag " + localName + " ignored");
		}

		public void endElement(String localName) {
			positionRecorder.removeLast();
		}

	}

	private interface Position {
		public void startElement(String localName, Attributes attr)
				throws SAXException;

		public void endElement(String localName) throws SAXException;

	}

	public void startParsing(String url) throws IOException, SAXException {		
			startParsing(new InputSource(url));				
	}
	
	public void startParsingFromFileOrClassPath(String path) throws IOException, SAXException {
		if(path.indexOf(CLASSPATH_URL_PREFIX) != -1){
			String resourcePath = path.substring(CLASSPATH_URL_PREFIX.length());
			InputStream resource = getClass().getClassLoader().getResourceAsStream(resourcePath);
			if(resource == null){
				throw new IOException("Unable to find sampling config file " + resourcePath + " in classpath");
			}
			startParsing(resource);
			resource.close();
		}else{
			startParsing(new File(path));
		}		
	}

	public void startParsing(File file) throws IOException, SAXException {
		InputStream stream = new FileInputStream(file);
		startParsing(new InputSource(stream));
		stream.close();
	}

	public void startParsing(InputStream in) throws IOException, SAXException {
		startParsing(new InputSource(in));
	}

	public void startParsing(Reader in) throws IOException, SAXException {
		startParsing(new InputSource(in));
	}

	private synchronized void startParsing(InputSource in) throws IOException,
			SAXException {
		xmlReader.setContentHandler(this);	
		xmlReader.parse(in);
	}

}