package com.brilliance.isc.utils;

import java.util.Map;
import java.util.Map.Entry;
import java.util.Stack;

public class XmlUtil {

    private static final String XML_HEAD = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
    private static final String PREFIX_XML = "<ROOT>\n";
    private static final String SUFFIX_XML = "</ROOT>";
    private static final String PREFIX_CDATA = "<![CDATA[";
    private static final String SUFFIX_CDATA = "]]>";

    /**
     * 转化成xml, 单层无嵌套 * @param map * @param isAddCDATA * @return
     */
    public static String mapToXml(Map<Object, Object> parm, boolean isAddCDATA) {
        Map<Object, Object> msgHead = (Map) parm.get("msgHead");
        Map<Object, Object> msgBody = (Map) parm.get("msgBody");
        StringBuilder strbuff = new StringBuilder(XML_HEAD);
        strbuff.append(PREFIX_XML);
        String space2 = "  ";
        String space4 = "    ";
        String[] spaces = {space2,space4,space2+space4,space4+space4,space4+space4+space2,space4+space4+space4};
        if (null != msgHead) {
            strbuff.append(space2).append("<MsgHead>\n");
            writeMap(strbuff,msgHead,isAddCDATA,spaces,1);
            strbuff.append(space2).append("</MsgHead>");
        }
        strbuff.append("\n");
        if (null != msgBody) {
            strbuff.append(space2).append("<MsgBody>\n");
            writeMap(strbuff,msgBody,isAddCDATA,spaces,1);
            strbuff.append(space2).append("</MsgBody>\n");
        }
        return strbuff.append(SUFFIX_XML).toString();
    }

    public static void writeMap(StringBuilder strbuff,Map<Object, Object> paramMap, boolean isAddCDATA,String[] spaces,int lvl){
        String space = spaces[lvl];
        for (Entry<Object, Object> entry : paramMap.entrySet()) {
            String xmlKey = entry.getKey().toString();
            strbuff.append(space).append("<").append(xmlKey).append(">");
            boolean hasSub = false;
            if(entry.getValue() instanceof Map){
                hasSub = true;
                strbuff.append("\n");
                writeMap(strbuff, (Map<Object, Object>) entry.getValue(),isAddCDATA,spaces,lvl+1);
            }else {
                if (isAddCDATA) {
                    strbuff.append(PREFIX_CDATA);
                    if (null != entry.getValue()) {
                        strbuff.append(entry.getValue());
                    }
                    strbuff.append(SUFFIX_CDATA);
                } else {
                    if (null != entry.getValue()) {
                        strbuff.append(entry.getValue());
                    }
                }
            }
            if(hasSub){
                //存在子元素，被折行了，所以要补空格
                strbuff.append(space);
            }
            strbuff.append("</").append(xmlKey).append(">");
            strbuff.append("\n");
        }
    }
}
