package com.cim.idm.wmsextend.generic.util;

import com.cim.idm.framework.util.xml.JdomUtils;
import com.tibco.tibrv.TibrvException;
import com.tibco.tibrv.TibrvMsg;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom.Document;
import org.jdom.Element;

public class LMessageUtil {

	private static 	Log 								log = LogFactory.getLog(LMessageUtil.class);
	
	public static final String 							BPELName_Tag = "bpelname";
	public static final String 							Message_Tag = "message";
	public static final String 							MessageName_Tag = "messagename";
//	public static final String 							Header_Tag = "header";
	public static final String 							Header_Tag = "HDR";
//	public static final String 							Body_Tag = "body";
	public static final String 							Body_Tag = "DATA";
	public static final String 							Result_Name_Tag				= "return";	        
	public static final String							Result_ReturnCode			= "returncode";
	public static final String							Result_ErrorMessage			= "returnmessage";
	
	private static final String 						ReplySubjectName_Tag = "replysubjectname";
	private static final Character						spaceDelimiter				= ' ';
	private static final Character						equalDelimiter				= '=';
	private static final Character						frontBraceDelimiter			= '{';
	private static final Character						backBraceDelimiter			= '}';
	private static final Character						commaDelimiter				= '"';
	
	
	/*
	* Name : getBpelName
	* Desc : This function is getBpelName
	* Author : ZXY Systems, Inc
	* Date : 2013.02.19
	*/
	public static String getBpelName(Document doc)                                    
	{                   
		String BpelName = null;
		try {           
			BpelName = (String) JdomUtils.getNodeText(doc, "//" + Message_Tag + "/" + Header_Tag + "/" + MessageName_Tag);
			if (BpelName != null && BpelName.length() > 0) {
				if (!BpelName.toLowerCase().endsWith(".bpel"))
					BpelName = BpelName + ".bpel";
			}
		} catch (Exception e) {                                                                 
		}                                                                                       
		return BpelName;                                                                              
	}      
	/*
	* Name : getDocumentFromTibrvMsg
	* Desc : This function is getDocumentFromTibrvMsg
	* Author : ZXY Systems, Inc
	* Date : 2013.02.19
	*/
	public static Document getDocumentFromTibrvMsg(TibrvMsg data, String dataFieldTag)
	{
		
		Document document = null;    
		String strMsg = "";
		String replySubjectName = "";
		if (data instanceof TibrvMsg)
		{
			TibrvMsg TibrvMsg = (TibrvMsg)data;
			try {
				strMsg = (String)TibrvMsg.get(dataFieldTag);
				replySubjectName = (String)TibrvMsg.getReplySubject();
				if (replySubjectName == null) replySubjectName = "";
					
			} catch (TibrvException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		try {
			Element messageElement = new Element(Message_Tag);
			int msgPosition = StringUtils.indexOf(strMsg, spaceDelimiter);
			String messageName = StringUtils.substring(strMsg, 0, msgPosition);
			String parseMsg = StringUtils.substring(strMsg, msgPosition + 1);
			if(StringUtils.isEmpty(messageName))
				throw new Exception("Not Found MessageName!!");
			convertXmlElement(messageElement, parseMsg);
			
			document = new Document(messageElement);
			setItemValue(document, Header_Tag, MessageName_Tag, messageName);
			
//			StringBuilder messageBuilder = new StringBuilder();
//			messageBuilder.append("<");
//			messageBuilder.append(Message_Tag);
//			messageBuilder.append(">");
//			
//			int msgPosition = StringUtils.indexOf(strMsg, spaceDelimiter);
//			String messageName = StringUtils.substring(strMsg, 0, msgPosition);
//			String parseMsg = StringUtils.substring(strMsg, msgPosition + 1);
//			if(StringUtils.isEmpty(messageName))
//				throw new Exception("Not Found MessageName!!");
//			convertXmlStringBuilder(messageBuilder, parseMsg);
//			messageBuilder.append("</");
//			messageBuilder.append(Message_Tag);
//			messageBuilder.append(">");
//			document = JdomUtils.loadText(messageBuilder.toString());
//			setItemValue(document, Header_Tag, MessageName_Tag, messageName);
			
			
		} catch (Exception ex) {
			log.error(ex, ex);
		}
		
		if ( replySubjectName.length() > 0 )
			setItemValue(document, Header_Tag, ReplySubjectName_Tag, replySubjectName);
		return document;
	}
	/*
	* Name : replyXMLMessage
	* Desc : This function is replyXMLMessage
	* Author : ZXY Systems, Inc
	* Date : 2013.02.19
	*/
	public static String replyXMLMessage(String ReturnCode)
	{
		Document doc = JdomUtils.createDocument(Message_Tag);
		SMessageUtil.setResultItemValue(doc, Result_ReturnCode, ReturnCode);
		SMessageUtil.setResultItemValue(doc, Result_ErrorMessage, "");
		String replyMSG = JdomUtils.toString(doc);
		return replyMSG;
	}
	/*
	* Name : setElement
	* Desc : This function is setElement
	* Author : ZXY Systems, Inc
	* Date : 2013.02.19
	*/
	public static void setElement(String nodePath, Document doc, String nodeName, String nodeValue)
	{
		if (nodeValue == null) nodeValue = "";
		try {
			Element element = JdomUtils.getNode(doc, nodePath + nodeName);
			if (element != null) {
				//element.setContent(new CDATA(nodeValue));
				//element.setContent(new Element(nodeValue));
				if (nodePath.substring(nodePath.length()-1 , nodePath.length()).equalsIgnoreCase("/"))
					nodePath = nodePath.substring(0, nodePath.length()-1);
				JdomUtils.setNodeText(doc, nodePath, nodeName, nodeValue);
			}
			else {
				//Element createElement = JdomUtils.createElement(nodeName, valueKey);
				if (nodePath.substring(nodePath.length()-1 , nodePath.length()).equalsIgnoreCase("/"))
					nodePath = nodePath.substring(0, nodePath.length()-1);
				Element parentElement = JdomUtils.getNode(doc, nodePath);
				Element newElement = JdomUtils.addElement(parentElement, nodeName, nodeValue);
				//newElement.setContent(new CDATA(nodeValue));
			}
		} catch (Exception e) {                                                                 
			e.printStackTrace();                                                                
		}                                                                                                                                                                  
	}
	
	/*
	* Name : setResultItemValue
	* Desc : This function is setResultItemValue
	* Author : ZXY Systems, Inc
	* Date : 2013.02.19
	*/
	public static void setResultItemValue(Document doc, String nodeName, String nodeValue)                                    
	{
		if (doc.getRootElement().getChild(Result_Name_Tag) == null)
			doc.getRootElement().addContent(new Element(Result_Name_Tag));
		
		String nodePath = "//" + Message_Tag + "/" + Result_Name_Tag + "/";
		setElement(nodePath, doc, nodeName, nodeValue);

		if (nodeName.equalsIgnoreCase(SMessageUtil.Result_ReturnCode) && !nodeValue.equalsIgnoreCase("0"))
			log.error(nodeName + " : " + nodeValue);
//		else if (nodeName.equalsIgnoreCase(SMessageUtil.Result_ReturnCode) && nodeValue.equalsIgnoreCase("0"))
//			log.info(MessageUtil.Return_Code + " : 0");
		else if (nodeName.equalsIgnoreCase(SMessageUtil.Result_ErrorMessage) && nodeValue.length() > 0)
			log.error(nodeName + " : " + nodeValue);
		else if  (nodeName.equalsIgnoreCase(SMessageUtil.Result_ErrorMessage) && nodeValue.length() == 0)
			log.error(nodeName + " : ");
		
		//log.debug("[" + nodeName + "] = " + nodeValue);
	}
	/*
	* Name : setReplyListItemValue
	* Desc : This function is setReplyListItemValue
	* Author : ZXY Systems, Inc
	* Date : 2013.02.19
	*/
	public static void setReplyListItemValue(Document doc,String Path, String nodeName, String nodeValue)                                    
	{
		if (doc.getRootElement().getChild(Result_Name_Tag) == null)
			doc.getRootElement().addContent(new Element(Result_Name_Tag));
		
		String nodePath = "//" + Message_Tag + "/" + Body_Tag + "/" + Path;
		setElement(nodePath, doc, nodeName, nodeValue);

		if (nodeName.equalsIgnoreCase(SMessageUtil.Result_ReturnCode) && !nodeValue.equalsIgnoreCase("0"))
			log.error(nodeName + " : " + nodeValue);
//		else if (nodeName.equalsIgnoreCase(SMessageUtil.Result_ReturnCode) && nodeValue.equalsIgnoreCase("0"))
//			log.info(MessageUtil.Return_Code + " : 0");
		else if (nodeName.equalsIgnoreCase(SMessageUtil.Result_ErrorMessage) && nodeValue.length() > 0)
			log.error(nodeName + " : " + nodeValue);
		else if  (nodeName.equalsIgnoreCase(SMessageUtil.Result_ErrorMessage) && nodeValue.length() == 0)
			log.error(nodeName + " : ");
		
		//log.debug("[" + nodeName + "] = " + nodeValue);
	}
	/*
	* Name : convertXmlStringBuilder
	* Desc : This function is convertXmlStringBuilder
	* Author : ZXY Systems, Inc
	* Date : 2013.02.19
	*/
	public static void convertXmlStringBuilder(StringBuilder message, String messageData) throws Exception
	{
		int itemCount = 0;
		int itemBPosition  = -1;
		int spacePosition  = 0;
		int bracePosition  = 0;
		int valueEPosition = 0;
		
		String stringName  = "";
		String stringValue = "";
		String currentStr  = "";
		String itemString  = "";
		
		for(int i = 0; i < messageData.length(); i++)
		{
			if(messageData.charAt(i) == '=' && itemCount == 0)
			{
				currentStr = StringUtils.substring(messageData, 0, i);
				spacePosition = StringUtils.lastIndexOf(currentStr, spaceDelimiter);
				bracePosition = StringUtils.lastIndexOf(currentStr, frontBraceDelimiter);
				
				if(spacePosition > bracePosition)
					stringName = StringUtils.substring(currentStr, spacePosition + 1, i);
				else if(spacePosition < bracePosition)
					stringName = StringUtils.substring(currentStr, bracePosition + 1, i);
				else
					stringName = StringUtils.substring(currentStr, 0, i);
			}
			if(messageData.charAt(i) == frontBraceDelimiter)
			{
				itemCount++;
				if(itemBPosition == -1)
				{
					itemBPosition = i;
				}
			}
			else if(messageData.charAt(i) == backBraceDelimiter)
			{
				itemCount--;
			}
			
			if(messageData.charAt(i) == backBraceDelimiter && itemCount == 0)
			{
				itemString = StringUtils.substring(messageData, itemBPosition + 1, i);
//				Element itemElement = new Element(stringName);
				StringBuilder itemBuilder = new StringBuilder();
				itemBuilder.append("<");
				itemBuilder.append(stringName);
				itemBuilder.append(">");
				
				convertXmlStringBuilder(itemBuilder, itemString);
				itemBuilder.append("</");
				itemBuilder.append(stringName);
				itemBuilder.append(">");
				message.append(itemBuilder);
//				message.addContent(itemElement);
				itemBPosition = -1;
			}
			
			if(messageData.charAt(i) == equalDelimiter && 
					messageData.charAt(i + 1) != frontBraceDelimiter && itemCount == 0)
			{
				currentStr = StringUtils.substring(messageData, 0, i);
				spacePosition = StringUtils.lastIndexOf(currentStr, spaceDelimiter);
				
				stringName = "";
				stringValue = "";
				if(spacePosition > 0)
					stringName = StringUtils.substring(currentStr, spacePosition + 1, i);
				else
					stringName = StringUtils.substring(currentStr, 0 ,i);
				
				valueEPosition = StringUtils.indexOf(messageData, commaDelimiter, i + 2);
				stringValue = StringUtils.substring(messageData, i + 2, valueEPosition);
//				Element tempItemElement = new Element(stringName);
//				tempItemElement.setText(stringValue);
				StringBuilder tempItemBuilder = new StringBuilder();
				tempItemBuilder.append("<");
				tempItemBuilder.append(stringName);
				tempItemBuilder.append(">");
				tempItemBuilder.append(stringValue);
				tempItemBuilder.append("</");
				tempItemBuilder.append(stringName);
				tempItemBuilder.append(">");
				
				message.append(tempItemBuilder);
//				message.addContent(tempItemElement);
			}
		}
	}
	/*
	* Name : convertXmlElement
	* Desc : This function is convertXmlElement
	* Author : ZXY Systems, Inc
	* Date : 2013.02.19
	*/
	public static void convertXmlElement(Element message, String messageData) throws Exception      
	{
		int itemCount = 0;
		int itemBPosition  = -1;
		int spacePosition  = 0;
		int bracePosition  = 0;
		int valueEPosition = 0;
		
		String stringName  = "";
		String stringValue = "";
		String currentStr  = "";
		String itemString  = "";
		
		for(int i = 0; i < messageData.length(); i++)
		{
			if(messageData.charAt(i) == '=' && itemCount == 0)
			{
				currentStr = StringUtils.substring(messageData, 0, i);
				spacePosition = StringUtils.lastIndexOf(currentStr, spaceDelimiter);
				bracePosition = StringUtils.lastIndexOf(currentStr, frontBraceDelimiter);
				
				if(spacePosition > bracePosition)
					stringName = StringUtils.substring(currentStr, spacePosition + 1, i);
				else if(spacePosition < bracePosition)
					stringName = StringUtils.substring(currentStr, bracePosition + 1, i);
				else
					stringName = StringUtils.substring(currentStr, 0, i);
			}
			if(messageData.charAt(i) == frontBraceDelimiter)
			{
				itemCount++;
				if(itemBPosition == -1)
				{
					itemBPosition = i;
				}
			}
			else if(messageData.charAt(i) == backBraceDelimiter)
			{
				itemCount--;
			}
			
			if(messageData.charAt(i) == backBraceDelimiter && itemCount == 0)
			{
				itemString = StringUtils.substring(messageData, itemBPosition + 1, i);
				Element itemElement = new Element(stringName);
				convertXmlElement(itemElement, itemString);
				message.addContent(itemElement);
				itemBPosition = -1;
			}
			
			if(messageData.charAt(i) == equalDelimiter && 
					messageData.charAt(i + 1) != frontBraceDelimiter && itemCount == 0)
			{
				currentStr = StringUtils.substring(messageData, 0, i);
				spacePosition = StringUtils.lastIndexOf(currentStr, spaceDelimiter);
				
				stringName = "";
				stringValue = "";
				if(spacePosition > 0)
					stringName = StringUtils.substring(currentStr, spacePosition + 1, i);
				else
					stringName = StringUtils.substring(currentStr, 0 ,i);
				
				valueEPosition = StringUtils.indexOf(messageData, commaDelimiter, i + 2);
				stringValue = StringUtils.substring(messageData, i + 2, valueEPosition);
				Element tempItemElement = new Element(stringName);
				tempItemElement.setText(stringValue);
				message.addContent(tempItemElement);
			}
		}
	}
	/*
	* Name : updateElement
	* Desc : This function is updateElement
	* Author : ZXY Systems, Inc
	* Date : 2013.02.19
	*/
	public static void updateElement(StringBuilder xmlMsgBuilder, String inputElementName){
		
	}
	/*
	* Name : setItemValue
	* Desc : This function is setItemValue
	* Author : ZXY Systems, Inc
	* Date : 2013.02.19
	*/
    public static void setItemValue(Document doc, String elementName, String nodeName, String nodeValue)                                    
	{                                                                                         
		try {
			String nodePath = "//" + Message_Tag + "/" + elementName + "/" + nodeName;
			Element element = JdomUtils.getNode(doc, nodePath);
			if (element != null)
				JdomUtils.setNodeText(doc, nodePath, nodeValue);     
			else {
				nodePath = "//" + Message_Tag + "/" + elementName + "/";
				if (nodePath.endsWith("/")) 
					nodePath = nodePath.substring(0, nodePath.length()-1);
				Element headerElement = JdomUtils.getNode(doc, nodePath);
				JdomUtils.addElement(headerElement, nodeName, nodeValue);
			}
		} catch (Exception e) {                                                                 
			log.error(e, e);
		}                                                                                                                                                                  	
	}    
	
//	private static  HashMap parsingStringMessage(String msg)
//	{
//		String delimeter = "[{X*X}]";  
//		
//		String msg2 = msg;
//		while(true)
//		{
//			int idx1 = msg2.indexOf("=[");
//			int idx2 = msg2.indexOf("]", idx1);
//			if (idx1 > 0 && idx2 > 0)
//			{
//				String a = msg2.substring(idx1+2, idx2);
//				if (a.length() == 0)
//				{
//					msg2 = msg2.substring(idx2+1, msg2.length()); continue;
//				}
//				String b = org.springframework.util.StringUtils.replace(a, "=", "($%^)");
//				msg = org.springframework.util.StringUtils.replace(msg, a, b);				
//				msg2 = msg2.substring(idx2, msg2.length());
//			}
//			else break;
//		}
//		
//		String [] messageSplit = msg.split("=");
//		HashMap<String, String> params = new HashMap<String, String>();
//		StringBuffer keyNameBuffer = new StringBuffer();
//		keyNameBuffer.append("Command").append(delimeter);
//		StringBuffer valueBuffer = new StringBuffer();
//		for (int i=0; i<messageSplit.length; i++)
//		{
//			if (getKeyName(messageSplit[i]).length() > 0) {
//				keyNameBuffer.append(getKeyName(messageSplit[i])).append(delimeter);
//				valueBuffer.append(getValue(messageSplit[i])).append(delimeter);
//			}
//			else {
//				valueBuffer.append(messageSplit[i]).append(delimeter);
//			}
//		}
//
//		String[] keyNames = org.springframework.util.StringUtils.delimitedListToStringArray(keyNameBuffer.toString(), delimeter);
//		String[] keyvalues = org.springframework.util.StringUtils.delimitedListToStringArray(valueBuffer.toString(), delimeter);
//		
//		//if (keyNames.length == (keyvalues.length+1))
//			
//			
//		for (int i=1; i<keyNames.length; i++)
//		{
//			if (keyNames[i] == null || keyNames[i].trim().length() == 0) continue;
//			try {
//				keyvalues[i] = keyvalues[i].trim();
//				keyvalues[i] = org.springframework.util.StringUtils.replace(keyvalues[i], "($%^)", "=");
//				if (keyvalues[i].startsWith("[") && keyvalues[i].endsWith("]"))
//					keyvalues[i] = keyvalues[i].substring(1, keyvalues[i].length()-1);
//				params.put(keyNames[i], keyvalues[i].trim());
//			} catch (Exception e) {
//				params.put(keyNames[i], "");
//				log.debug("Value of last data is empty");
//			}
//		}
//		return params;
//	}	
//	private static String getKeyName(String partialMsg)
//	{
//		if (partialMsg.startsWith("[") && partialMsg.endsWith("]"))
//			return "";
//		String character = "";
//		String value = "";
//		for (int i=partialMsg.length(); i>0; i--)
//		{
//			character = partialMsg. substring(i-1, i);
//			if (character.equalsIgnoreCase(" "))
//			{
//				return StringUtils.reverse(value);
//			}
//			else {
//				value += character;
//			}
//		}
//		return "";
//	}

//	private static String getValue(String partialMsg)
//	{
//		partialMsg = StringUtils.removeEnd(partialMsg, getKeyName(partialMsg));
//		try {
//			if (partialMsg.trim().length() == 0)
//				return "";
//		} catch (Exception e) {}
//		return partialMsg;
//	}
}
