package csa.tiletools.map;

import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.*;
import java.util.*;
public class  ColorTileMapXMLHandler extends DefaultHandler
{
	private HashMap<String, ColorTileMap> mColorTileMap;
	private ColorTileMap mCurrentData = null;
	private String mCurrentElement = null;
	private String mColor = "";
	private Vector<Integer> mColors = null;
	private String mTileFile = "";
	private Vector<String> mTileFiles = null;
	private String mTileName = "";
	private Vector<String> mTileNames = null;
	public HashMap<String, ColorTileMap> getLastHashMap()
	{
		return mColorTileMap;
	}
	@Override public void startDocument() throws SAXException
	{
		mCurrentData = new ColorTileMap();
		mColorTileMap = new HashMap<String, ColorTileMap>();
	}
	@Override public void endDocument () throws SAXException
	{
	}
	@Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
	{
		mCurrentElement = qName;
		if (qName.equalsIgnoreCase("ColorTileMap"))
		{
			mCurrentData = new ColorTileMap();
			mColor = "";
			mColors = new Vector<Integer>();
			mTileFile = "";
			mTileFiles = new Vector<String>();
			mTileName = "";
			mTileNames = new Vector<String>();
		}
	}
	@Override public void characters(char[] ch, int start, int length)
	{
		String s = new String( ch, start, length );
		if (mCurrentElement == null) return;
		if (mCurrentElement.equalsIgnoreCase("Class")) mCurrentData.mClass += s;
		if (mCurrentElement.equalsIgnoreCase("Name")) mCurrentData.mName += s;
		if (mCurrentElement.equalsIgnoreCase("Color")) mColor += s;
		if (mCurrentElement.equalsIgnoreCase("TileFile")) mTileFile += s;
		if (mCurrentElement.equalsIgnoreCase("TileName")) mTileName += s;
	}
	@Override public void endElement(String uri, String localName, String qName) throws SAXException
	{
		if ("Color".equalsIgnoreCase(qName))
		{
			try{
			mColors.addElement(Integer.parseInt(mColor));
			}catch (Throwable e){}
			mColor="";
		}
		if ("TileFile".equalsIgnoreCase(qName))
		{
			mTileFiles.addElement(mTileFile);
			mTileFile="";
		}
		if ("TileName".equalsIgnoreCase(qName))
		{
			mTileNames.addElement(mTileName);
			mTileName="";
		}
		if ("ColorTileMap".equalsIgnoreCase(qName))
		{
			if (mCurrentData != null)
			{
				mColor = "";
				mCurrentData.mColor = mColors;
				mTileFile = "";
				mCurrentData.mTileFile = mTileFiles;
				mTileName = "";
				mCurrentData.mTileName = mTileNames;
				mColorTileMap.put(mCurrentData.mName, mCurrentData);
				mCurrentData = null;
			}
		}
		mCurrentElement = null;
	}
}
