package cn.amq.basis;



import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;

public class AmqBasisEvent {
	private org.dom4j.Document outDocument=DocumentHelper.createDocument();
	public org.dom4j.Document inDocument=null;
	protected String msgType;
	protected Element outMsgTypeElement=null;
	public static String readMessageType(String text) throws Exception{
			org.dom4j.Document document =DocumentHelper.parseText(text);
			Element element=(Element) document.selectSingleNode("/amq");
			String type=element.attributeValue("type");
			return type;
	}
	public void writeObjToXml(){
		 outDocument.setXMLEncoding("gb2312");
		 outMsgTypeElement = outDocument.addElement("amq");
		 outMsgTypeElement.addAttribute("type",msgType);
	}
	public void readTextToObject(String text) throws Exception{
		this.inDocument=DocumentHelper.parseText(text);
		Element element=(Element) inDocument.selectSingleNode("/amq");
		this.msgType=element.attributeValue("type");
	}
	final public Element getOutMsgTypeElement(){
		return outMsgTypeElement;
	}
	final public Document getOutDocument(){
		return outDocument;
	}
	public String getMsgType() {
		return msgType;
	}
	public void addTextToElement(Element element,String key,String value){
		if(value==null)element.addElement(key).addText("");
		else element.addElement(key).addText(value);
	}
	public void addTextToElement(Element element,String key,int value){
		element.addElement(key).addText(Integer.toString(value));
	}
	public void addTextToElement(Element element,String key,long value){
		element.addElement(key).addText(Long.toString(value));
	}
	public int readIntByFullPath(String fullPath){
		Node node=this.inDocument.selectSingleNode(fullPath);
		String value=node.getText();
		if(value!=null&&value.length()!=0) return Integer.parseInt(node.getText());
		else return 0;
	}
	public long readLongByFullPath(String fullPath){
		Node node=this.inDocument.selectSingleNode(fullPath);
		String value=node.getText();
		if(value!=null&&value.length()!=0) return Long.parseLong(node.getText());
		else return 0;
	}
	public String readStringByFullPath(String fullPath){
		Node node=this.inDocument.selectSingleNode(fullPath);
		if(node==null)return "";
		else return node.getText();
	}
	public int readIntFromElement(Element element,String key){
		Element tmpElement=(Element) element.selectSingleNode(key);
		if(tmpElement==null)return 0;
		String value=tmpElement.getText();
		if(value!=null&&value.length()!=0) return Integer.parseInt(value);
		else return 0;
	}
	public String readStringFromElement(Element element,String key){
		Element tmpElement = (Element) element.selectSingleNode(key);
		if (tmpElement == null) {
			return "";
		}
		String value=tmpElement.getText();
		return value;
	}
	public void setMsgType(String msgType) {
		this.msgType = msgType;
	}
}
