package webchurch.parse;


import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class ParseData {
	private HashMap map = new HashMap();
	private Document dom;

	public ParseData() {
	}

	public HashMap getData(String fileName) {
		fileName = "D:\\CONF\\fileUpload\\" + fileName;	
		parseXmlFile(fileName);
		parseDocument();
		return map;
	}

	private void parseDocument() {
		// TODO Auto-generated method stub
		Element docEle = dom.getDocumentElement();
		NodeList nl = docEle.getElementsByTagName("URL");
		if (nl != null && nl.getLength() > 0) {
			for (int i = 0; i < nl.getLength(); i++) {
				Element el = (Element) nl.item(i);

				getURL(el);

			}
		}

	}

	private void getURL(Element el) {
		// TODO Auto-generated method stub
		Object inValue;
		String value = getTextValue(el, "value");
		String key = el.getAttribute("name");
		if(map.containsKey(key)){
			if(map.get(key) instanceof String){
				ArrayList ar = new ArrayList();
				ar.add(map.get(key));
				ar.add(value);
				inValue = ar;
			}else{
				ArrayList ar = (ArrayList) map.get(key);
				ar.add(value);
				inValue = ar;
			}
		}else{
			inValue = value;
		}
		map.put(key, inValue);
	}

	private String getTextValue(Element el, String string) {
		// TODO Auto-generated method stub
		String textVal = null;
		NodeList nl = el.getElementsByTagName(string);
		if(nl != null && nl.getLength() > 0){
			Element ele = (Element)nl.item(0);
			textVal = ele.getFirstChild().getNodeValue();
			//System.out.println(textVal);
		}
		return textVal;
	}

	private void parseXmlFile(String fileName) {
		// TODO Auto-generated method stub
		DocumentBuilderFactory builderFactory = DocumentBuilderFactory
				.newInstance();

		try {
			DocumentBuilder builder = builderFactory.newDocumentBuilder();
			dom = builder.parse(fileName + ".xml");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println("parseDocumentError : " + e.getMessage());
		}
	}
}