package cn.com.poc.user.wecom.util;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * XML解析器
 */
class XMLParse {

    public static Object[] extract(String xmltext) throws AesException {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
            DocumentBuilder db = dbf.newDocumentBuilder();
            InputStream inputStream = new ByteArrayInputStream(xmltext.getBytes(StandardCharsets.UTF_8));
            Document doc = db.parse(inputStream);
            Element root = doc.getDocumentElement();
            NodeList nodelist1 = root.getElementsByTagName("Encrypt");
            NodeList nodelist2 = root.getElementsByTagName("ToUserName");
            if (nodelist1.getLength() == 0) {
                throw new AesException(AesException.ParseXmlError);
            }
            String encrypt = nodelist1.item(0).getTextContent();
            String toUserName = nodelist2.item(0).getTextContent();
            return new Object[]{toUserName, encrypt};
        } catch (Exception e) {
            throw new AesException(AesException.ParseXmlError);
        }
    }

    public static String generate(String encrypt, String signature, String timestamp, String nonce) {
        return "<xml>\n" +
                "<Encrypt><![CDATA[" + encrypt + "]]></Encrypt>\n" +
                "<MsgSignature><![CDATA[" + signature + "]]></MsgSignature>\n" +
                "<TimeStamp>" + timestamp + "</TimeStamp>\n" +
                "<Nonce><![CDATA[" + nonce + "]]></Nonce>\n" +
                "</xml>";
    }
}
