package com.eactive.eai.common.util;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class XMLUtils {
	
	private XMLUtils() {
		throw new IllegalStateException("Utility class");
	}
	
	public static Document convertXmlDocument(Object message) throws DocumentException {
		if (message == null)
			return DocumentHelper.createDocument();
		else if (message instanceof Document)
			return (Document) message;
		else if  (message instanceof String) {
			SAXReader builder = new SAXReader();
			return builder.read(new StringReader((String)message));
		} else
			throw new IllegalArgumentException("not support xml type. " + message.getClass());
	}
	
	public static List<Element> getChilds(Element parent) {
		List<Element> elements = new ArrayList<>();
		Iterator<Element> iterator = parent.elementIterator();
		while(iterator.hasNext()) {
			Element child = iterator.next();
			elements.add(child);
			elements.addAll(getChilds(child));
		}
		return elements;
	}
	
	public static List<Element> getChildsLevel1(Element parent) {
		List<Element> elements = new ArrayList<>();
		Iterator<Element> iterator = parent.elementIterator();
		while(iterator.hasNext()) {
			Element child = iterator.next();
			elements.add(child);
		}
		return elements;
	}
	
	@SuppressWarnings("unchecked")
	public static Object elementToJSONObject(Element element) {
		JSONObject json = new JSONObject();
		
		List<Element> children = element.elements();
		if(children.isEmpty()) {
			return element.getText();
		}
		for(Element child : children) {
			String childName = child.getName();
			if(json.containsKey(childName)) {
				Object existing = json.get(childName);
				if(existing instanceof JSONArray) {
					((JSONArray) existing).add(elementToJSONObject(child));
				} else {
					JSONArray list = new JSONArray();
					list.add(existing);
					list.add(elementToJSONObject(child));
					json.put(childName, list);
				}
			} else {
				json.put(childName, elementToJSONObject(child));
			}
		}
		
		return json;
	}
	
	public static Element getElement(Element parent, String path) {
		String[] keys = path.split("\\.");
		Element current = parent;
		for(String key : keys) {
			current = current.element(key);
		}
		return (Element) current.elements().get(0);
	}
	

}
