/**
 * Copyright (c) 2004, yher2 project
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * * Redistributions of source code must retain the above copyright notice, 
 *   this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright notice, 
 *   this list of conditions and the following disclaimer in the documentation 
 *   and/or other materials provided with the distribution.
 * * Neither the name of the nor the names of its contributors may be used to endorse or 
 *   promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
 * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 
 * SUCH DAMAGE.
 */
package net.yher2.junit.db.data;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringEscapeUtils;

/**
 * @auther  hisaboh
 */
public class XmlParser {
	private String rawVal;
	private String xml;
	private String elementName;
	private Map attributeMap;
	
	
	public XmlParser(String xml) {
		this.rawVal = xml;
		attributeMap = new HashMap();
		normalize();
	}
	
	public String getXml() {
		return xml;
	}
	
	public boolean isXml() {
		return xml.matches("^<[^<>]+/>$");
	}
	
	public String getElementName() {
		return elementName;
	}
	
	public String getAttribute(String name) {
		return (String)attributeMap.get(name);
	}
	public boolean hasAttribute(String name) {
		return attributeMap.containsKey(name);
	}
	
	public void parse() {
		if (!isXml()) throw new IllegalArgumentException("This is not xml("+rawVal+")");
		String xmlString = xml.replaceAll("[</>]", "");
		String str[] = xmlString.split("[ ]");
		elementName = str[0].toLowerCase();
		if (!elementName.matches("[a-zA-Z]+")) {
			throw new IllegalArgumentException("Invalid Element Name("+elementName+")");
		}
		for (int i=1; i<str.length; i++) {
			parseAttribute(str[i]);
		}
	}
	
	private void parseAttribute(String attribute) {
		String str[] = attribute.split("=");
		if (str.length != 2) {
			throw new IllegalArgumentException("Invalid attribute("+attribute+")");
		}
		String name = str[0].toLowerCase();
		String value = str[1].replaceAll("\"", "");
		value = URLDecoder.decode(value);
		value = StringEscapeUtils.unescapeXml(value);
		attributeMap.put(name, value);
	}
	
	public void normalize() {
		StringBuffer buf = new StringBuffer();
		char c[] = rawVal.toCharArray();
		 
		boolean inQuote = false;
		for (int i=0; i<c.length; i++) {
			switch (c[i]) {
			case '"':
				inQuote = !inQuote;
				buf.append(c[i]);
				break;
			default:
				if (inQuote) {
					buf.append(URLEncoder.encode("" +c[i]));
				} else {
					buf.append(c[i]);
				}
				break;
			}
		}
		String result = buf.toString();
		result = result.replaceAll("[\n\r\t]", " ");
		result = result.replaceAll("[ ]+", " ");
		result = result.replaceAll("^[ ]+", "");
		result = result.replaceAll("[ ]+$", "");
		result = result.replaceAll("[ ]*=[ ]*", "=");
//		 result = URLDecoder.decode(result);
		 
		xml = result;
	}
}
