package ibase.communication.utility;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.StringTokenizer;

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

import ibase.system.config.ConnDriver;
import ibase.utility.BaseLogger;
import ibase.utility.E12GenericUtility;
import ibase.utility.UserInfoBean;
import ibase.webitm.ejb.ActionHandlerEJB;
import ibase.webitm.utility.ITMException;

public class CommUtility {

	public String getValue(String currToken, String xmlString, UserInfoBean userInfoBean) throws Exception {
		String result = "";
		if(currToken.indexOf("df_") != -1) {
		    BaseLogger.log("3", null, null, "To with 'df_' :[" + currToken + "]");
		    int startBracket = currToken.indexOf("<");
		    int endBracket = currToken.indexOf(">");
		    if (startBracket != -1 && endBracket != -1) {
		        String trimmedToken = currToken.substring(startBracket, endBracket + 1);
				BaseLogger.log("2",null,null,"E12SMSComp.sendSMS trimmedToken:: ["+trimmedToken+"]");						        
		        String argument = customizeDataStr(trimmedToken, xmlString);
				BaseLogger.log("2",null,null,"E12SMSComp.sendSMS argument:: ["+argument+"]");						        
		        String functionName = currToken.substring(0, startBracket);
				BaseLogger.log("2",null,null,"E12SMSComp.sendSMS functionName:: ["+functionName+"]");						        
		        result = executeSQLFunction(functionName, argument, userInfoBean);
				BaseLogger.log("2",null,null,"E12SMSComp.sendSMS result:: ["+result+"]");						        
		    }
		}
		else if ( currToken.indexOf("<") != -1 )
		{
			BaseLogger.log("3",null,null,"To with '<' :["+currToken+"]");
			result = customizeDataStr(currToken, xmlString);
		}
		else
		{
			result = currToken;
		}
		BaseLogger.log("3",null,null,"result :::["+result+"]");
		return result;
	}
	
	private String customizeDataStr(String fieldName, String domString)throws Exception//prerna
	{
		String fieldValue ="";
		String replacedFieldValue ="";
		String currMsgstr ="";
		StringBuffer msgBuff = new StringBuffer();
		try
		{
			BaseLogger.log("3",null,null, "fieldName:: "+fieldName);
			BaseLogger.log("3",null,null, "domString:: "+domString);


			if(fieldName.indexOf("<") != -1)
			{
				StringTokenizer msgToken = new StringTokenizer(fieldName,">");
				BaseLogger.log("3",null,null, "msgToken:: "+msgToken);
				while(msgToken.hasMoreTokens())
				{
					currMsgstr = msgToken.nextToken();
					if(currMsgstr.indexOf("<") != -1 )
					{
						int startBracket = currMsgstr.indexOf("<");
						msgBuff.append(currMsgstr.substring(0, startBracket));
						fieldValue = currMsgstr.substring(startBracket+1, currMsgstr.length());
						replacedFieldValue = getValueOfFieldFromDom(domString, fieldValue);
						BaseLogger.log("3",null,null, "replacedFieldValue:: "+replacedFieldValue);

						msgBuff.append(replacedFieldValue);
					}
				}
				if(!(fieldName.endsWith(">")))
				{
					String tempStr = fieldName.substring(fieldName.lastIndexOf(">")+1,fieldName.length());
					BaseLogger.log("3",null,null, "tempStr:: "+tempStr);
					msgBuff.append(tempStr);
				}
			}
			else
			{
				msgBuff.append(fieldName);
			}
			BaseLogger.log("3",null,null," msg buff ["+msgBuff.toString());
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return (msgBuff.toString());
	}
	
	
	private String getValueOfFieldFromDom(String domStr,String fieldRequired)throws Exception
	{
		Node parentNode = null;
		Document dom =null;
		String childNodeName = null;	
		String childNodeName1 = null;
		String fieldValue = null;
		String fromNode =null;
		ArrayList taskList = new ArrayList();
		try
		{
			E12GenericUtility genericUtility = new E12GenericUtility();
			dom = genericUtility.parseString(domStr);
			if(fieldRequired.indexOf(".") != -1)
			{
				fromNode = fieldRequired.substring(0,fieldRequired.indexOf("."));
				fieldRequired = fieldRequired.substring(fieldRequired.indexOf(".")+1,fieldRequired.length());
			}
			else
			{
				fromNode = (fromNode == null)?"Detail1":fromNode;
			}			
			NodeList detailList = dom.getElementsByTagName(fromNode);
			int detListLength = detailList.getLength();
			for(int ctr = 0; ctr < detListLength; ctr++)
			{
				Node currDetailNode = detailList.item(ctr);
				NodeList childList = currDetailNode.getChildNodes();
				int childCtr = childList.getLength();
				for(int chCnt=0; chCnt<childCtr; chCnt++)
				{
					Node childNode = childList.item(chCnt);
					childNodeName = childNode.getNodeName();
					if(childNodeName.equalsIgnoreCase(fieldRequired) && childNode.getFirstChild() != null)
					{
						fieldValue = childNode.getFirstChild().getNodeValue().trim();

						BaseLogger.log("3",null,null,"fieldRequired ["+fieldRequired+"] fieldValue  ["+fieldValue+"]");
					}					
				}
			}
			fieldValue = (fieldValue == null)?"":fieldValue;
		}
		catch(Exception e)
		{
			throw e;			
		}
		return (fieldValue);
	}
	
	
	private String executeSQLFunction(String functionName, String argument, UserInfoBean userInfoBean) throws ITMException {
		BaseLogger.log("2",null,null,"Calling executeSQLFunction method ["+functionName +"::"+argument+"]");
	    Connection conn = null;
	    CallableStatement callableStatement = null;
	    ActionHandlerEJB actionHandlerEJB = new ActionHandlerEJB();
	    String result = null;
	    ConnDriver connDriver = new ConnDriver();

	    try {
	        conn = connDriver.getConnectDB(userInfoBean.getTransDB());

	        String sql = "{ ? = call " + functionName + "(?) }";
			BaseLogger.log("2",null,null,"E12SMSComp.executeSQLFunction functionBody ["+sql+"]");
	        callableStatement = conn.prepareCall(sql);
	        callableStatement.registerOutParameter(1, Types.VARCHAR);
	        callableStatement.setString(2, argument);
	        callableStatement.execute();
	        result = callableStatement.getString(1);
			BaseLogger.log("2",null,null,"E12SMSComp.executeSQLFunction result:: ["+result+"]");
	    } 
	    catch (Exception e) {
	    	BaseLogger.log("3", null, null, "Exception in E12SMSComp.executeSQLFunction [" + E12GenericUtility.getStackTrace(e) + "]");
            throw new ITMException(e);	    } 
	    finally {
	        try {
	            if (callableStatement != null) {
	                callableStatement.close();
	            }
	            if (conn != null) {
	                conn.close();
	            }
	        } catch (SQLException se) {
	            se.printStackTrace(); 
	        }
	    }
	    return result; 
	}
}