package my.com.kfh.enterprise.services.ib117_jomPay;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.math.BigDecimal;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;

import my.com.kfh.enterprise.services.ESBServices;
import my.com.kfh.enterprise.services.GenericESBServicesImpl;
import my.com.kfh.enterprise.services.IBEnterpriseServices;
import my.com.kfh.enterprise.services.IBEnterpriseServicesWorkspace;
import my.com.kfh.enterprise.services.IBUtilsOnlineAcc;
import my.com.kfh.enterprise.services.common.CommonConstants;
import my.com.kfh.enterprise.services.ib101_access.AccessConstants;
import my.com.kfh.enterprise.services.ib101_access.IBAccessDBUtils;
import my.com.kfh.enterprise.services.ib105_billpayment.IBGenericPaymentServices;
import my.com.kfh.enterprise.services.ib105_billpayment.IBPaymentUtils;
import my.com.kfh.enterprise.services.ib105_billpayment.constant.BillPaymentContants;
import my.com.kfh.enterprise.services.ib112_si.IBGenericSIServices;
import my.com.kfh.enterprise.services.ib112_si.SIConstants;
import my.com.kfh.enterprise.services.ib112_si.SIDBUtils;
import my.com.kfh.enterprise.services.ib112_si.SI_PAYMENT_MODE;
import my.com.kfh.enterprise.services.ib116_online_acc.constant.OnlineAccConstants;
import my.com.kfh.enterprise.services.integration.ESBIntegrationConfig;
import my.com.kfh.error.exception.IBBusinessException;
import my.com.kfh.error.exception.IBGenericException;
import my.com.kfh.error.exception.IBServiceException;
import my.com.kfh.error.handler.CommonErrorCode;
import my.com.kfh.error.handler.IBErrorHandler;
import my.com.kfh.esb.response.ESBAccountDetailsBean;
import my.com.kfh.esb.response.ESBAccountEnquiryTC100Bean;
import my.com.kfh.esb.response.ESBCompanyProfileBean;
import my.com.kfh.esb.response.ESBTransferToGLBean;
import my.com.kfh.hibernate.tables.IBJomPay;
import my.com.kfh.hibernate.utils.HibernateJomPayUtils;
import my.com.kfh.integration.OnlineAccPromoBean;
import my.com.kfh.sms.services.SMSServices;
import my.com.kfh.web.utils.BVI_DateTime;
import my.com.kfh.web.utils.DataValidator;
import my.com.kfh.web.utils.DateTimeUtils;
import my.com.kfh.web.utils.FormatterUtils;
import my.com.kfh.web.utils.IBDynaBean;
import my.com.kfh.web.utils.IBLogger;
import my.com.kfh.web.utils.IBSessionObjects;
import my.com.kfh.web.utils.IBTimer;
import my.com.kfh.web.utils.ResourcesUtils;
import my.com.kfh.web.utils.constant.ESBConstants;
import my.com.kfh.web.utils.constant.LogTables;
import my.com.kfh.web.utils.constant.ServiceInfo;

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

import com.broadvision.data.client.DataManager;
import com.broadvision.data.common.TableData;
import com.kfh.nbps.webservice.NBPSWS1;
import com.kfh.nbps.webservice.NBPSWS1Service;
import com.kfh.nbps.webservice.NBPSWS1ServiceLocator;

public class IBOpenJomPaySIResultServices  {

	private static Class c_oClass = IBOpenJomPaySIResultServices.class;
	
	//Xml Response
	//WebService Response
	private static String xmlResponse1			=	null;
	private static String respStatus1			=	null;
	private static String respErrCode1			=	null;
	private static String respErrMsg1			=	null;
	private static String respJomPayRefNo1		=	null;
	private static String respDateTime1			=	null;
	private static String respRtnRequired1		=	null;
	private static String respRrnDynamic1		=	null;
	private static String respRrnInfo1			=	null;
	private static String respBillerName1		=	null;
	private static String respBillerCode1		=	null;
	private static String respBillerCodeName1	=	null;
	private static String respBillerAccount1	=	null;
	private static String respRfiRouteNo1		=	null;
	private static String respMsic1				=	null;
	private static String respChannelRefNo1		=	null;
		
	private static String xmlResponse = null;
	private static String respStatus = null;
	private static String respErrCode = null;
	private static String respErrMsg = null;
	private static String respJomPayRefNo = null;
	private static String respDateTime = null;
	private static String respChannelRefNo = null;
	private static String respChargeReferenceNo = null;
	private static String respChargeRespCode = null;
	private static String respFundReferenceNo = null;
	private static String respFundRespCode = null;
	
	public static void executeTransaction(String siId) throws Exception {
		
		String m_sMethodName = "executeServices";
		IBTimer m_oTimer = IBLogger.logBSFNMethodEnteringMessage (c_oClass, m_sMethodName);
		
		Date dt = new Date();
		
		Map<String, String> m_oReceiptMap = new LinkedHashMap<String, String> ();
		
		IBDynaBean viewBean = null;
		IBDynaBean m_oAccountFrom = null;
		
		double m_dAvailableBal = 0.0;
		boolean m_boIsFundSufficient = true;
		boolean m_boIsResultSuccessful = false;
		
		String m_sTrnxTypeAll = null;
		String m_sTransStatusMsg 	= null;
		String m_sReason = null;
		String m_sDate = null;
		String m_sTime = null;
		
		String m_sChargesAmount = null;
		String m_sReceiptLink = null;
		
		String m_sSIServiceCode = "";
		
		// DB
		String m_sStatus = null;
		String m_sMerchantAccNo = null;
		String m_sEPayReference = null;
		String m_sRevertReference = null;
		
		//WebService
		String channel				=	null;
		String subChannel			=	null;
		String fromAccountNo 		=	null;			 	
		String toAccountNo  		=	null;
		String amount  				=	null;
		String chargeAmount  		=	null;
		String toName  				=	null;
		String fromName  			=	null;
		String paymentDescription  	=	null;
		String phnxChargesDesc  	=	null;
		String phnxPrincipleDesc  	=	null;
		String channelRefNo			=	null;
		String paymentType  		=	null;
		String accountType  		=	null;
		String recipientRefNo   	=	null;
		String recipientRefNo2   	=	null;
		String billerCode   		=	null;
		String paymentChannel    	=	null;
		String payerType    		=	null;
		String chargesColAccount	=	null;
		String jomPayRefNo			=	null;
		
		BVI_DateTime m_oDate = null;
		
		String m_sEsbDescription = null;
		
		String m_sSICharges = "0";
		String m_sSIChargesRefNo = null;
		boolean m_boSIChargeStatus = false;
		double m_dTransferAmount = 0.0;
		double m_dTotalAmount = 0.0;
		double m_dSICharges = 0.0;
		String m_sSIChargeResponseCode = null;
		boolean m_boRevertStatus = false;
		
		String m_sChargeGLAccount = "";
		String m_sSIChargesRevertRefNo = null;
		boolean m_boSIChargeRevertStatus = false;
		
		//#-- added by pixa 20121017 start
		OnlineAccPromoBean onlineAccSIPromoBean=null;	
		OnlineAccPromoBean onlineAccTrnxPromoBean=null;	
		//#-- added by pixa 20121017 end
		
		String m_sAccNewBal="";
		
		try 
		{
			m_oDate = new BVI_DateTime ();
			m_sDate = DateTimeUtils.formatDayMonthYear (m_oDate);
			m_sTime = m_oDate.getTime ();

			//mock up
			IBSessionObjects m_oSessionObj = mock(IBSessionObjects.class);
			when(m_oSessionObj.getDataManager()).thenReturn(new DataManager());
			when(m_oSessionObj.getRemoteIPAddress ()).thenReturn("127.0.0.1");

			TableData table = SIDBUtils.getSICurrentTransId(new IBEnterpriseServicesWorkspace(m_oSessionObj), siId);
			String currentTrnxId  = table.getStringValue(0, LogTables.IB_SI.CURRENT_TRNX_ID.toString ());
			String siPaymentModeCode = table.getStringValue(0, LogTables.IB_SI.PAYMENT_MODE.toString ());
			String trnxTypeDisplay = table.getStringValue(0, LogTables.IB_SI.TRNX_TYPE.toString ());
			
			m_sSIServiceCode = table.getStringValue (0, LogTables.IB_SI.SERVICE_CODE.toString ());
			m_sEsbDescription = ESBConstants.JOMPAY;
			m_sEsbDescription = IBGenericSIServices.getESBDescription (m_sEsbDescription, siPaymentModeCode);
			String m_sEsbDescriptionCharges = m_sEsbDescription+":Charges";
			String m_sEsbDescriptionRevertCharges = m_sEsbDescription+":Revert Charges";

			IBEnterpriseServices p_oEnterpriseServices = new IBEnterpriseServicesWorkspace(m_oSessionObj);
			
			//get user id from trnx
			table = IBJomPayUtils.getTransactionByTrnxId(p_oEnterpriseServices, currentTrnxId);
			String userId = table.getStringValue(0, LogTables.IB_JOMPAY.USER_ID.toString ());
			com.broadvision.visitor.client.Visitor visitor = mock(com.broadvision.visitor.client.Visitor.class);
			when(visitor.getId()).thenReturn(Long.parseLong(userId));
			when(m_oSessionObj.getVisitor()).thenReturn(visitor);
			
			//get various data from transaction
			String m_sFromAccount = table.getStringValue(0, LogTables.IB_JOMPAY.FROM_ACC_NO.toString ());
			String m_sToAccount = table.getStringValue(0, LogTables.IB_JOMPAY.MERCHANT_ACC_NO.toString ());
			String m_sAmount = table.getStringValue(0, LogTables.IB_JOMPAY.AMOUNT.toString ());
			String fromCurrency = table.getStringValue(0, LogTables.IB_JOMPAY.FROM_CURRENCY.toString ());
			String toCurrency = table.getStringValue(0, LogTables.IB_JOMPAY.TO_CURRENCY.toString ());
			String m_sCharges = "0";
			String merchant = table.getStringValue(0, LogTables.IB_JOMPAY.BILLER_CODE.toString ());
			String merchantName = table.getStringValue(0, LogTables.IB_JOMPAY.BILLER_NAME.toString());
			String m_sBillAccountNo = table.getStringValue(0, LogTables.IB_JOMPAY.MERCHANT_ACC_NO.toString ());
			String m_sAccountNo = m_sFromAccount;
			String ref1 = table.getStringValue(0, LogTables.IB_JOMPAY.BILL_REF_NO1.toString ());
			String ref2 = table.getStringValue(0, LogTables.IB_JOMPAY.BILL_REF_NO2.toString ());
//			String m_sProductCode = table.getStringValue(0, LogTables.IB_JOMPAY.PRODUCT_CODE.toString ());
			String p_sInfo2 = table.getStringValue(0, LogTables.IB_JOMPAY.INFO2.toString ());
			String p_sInfo3 = table.getStringValue(0, LogTables.IB_JOMPAY.INFO3.toString ());
			String desc = table.getStringValue(0, LogTables.IB_JOMPAY.OTHER1.toString ());
			String jomPayRef = table.getStringValue(0, LogTables.IB_JOMPAY.JOMPAY_REF_NO.toString ());
			
			//get user rim no
			String rimNo = IBAccessDBUtils.getRimNoByUserId(p_oEnterpriseServices, userId);
			when(m_oSessionObj.getHttpSessionAttrObject (AccessConstants.RIM_NO)).thenReturn(rimNo);
			
			//no store payment type? just find in trnxtype display, search for open or favourite, no prepaid in si
			String m_sTrnxID 	= siId;//IBUtils.getTransactionId (new DataManager ());
			String m_sTrnxType = trnxTypeDisplay;
			
			//Set before calling to host
			fromAccountNo		= 	m_sFromAccount;
			
			ESBAccountDetailsBean acctResp = p_oEnterpriseServices.getESBServices().getAccountDetails(m_sFromAccount);
			ESBCompanyProfileBean profile = p_oEnterpriseServices.getESBServices().getProfileByAccRim(fromAccountNo, null);
			
			//Setting input for WebService 1
			channel 			= 	JomPayContants.jomPayWSChannel;//HD
			subChannel 			= 	JomPayContants.jomPayWSSubChannel;//HD
			amount				=	m_sAmount;
			channelRefNo		=	String.valueOf(m_sTrnxID);
			accountType			=	acctResp.getAccountType().toString().equalsIgnoreCase("SV")?"1":"2";
			recipientRefNo		=	ref1;
			recipientRefNo2		=	ref2;
			billerCode			=	merchant;
			paymentChannel		=	JomPayContants.jomPayWSPaymentChannel;
			
			//NBPS WebService Start
			xmlResponse = kfhWS1(channel,subChannel,amount,channelRefNo,accountType,recipientRefNo,recipientRefNo2,billerCode,paymentChannel);
			readXmlResponse1(xmlResponse);
			//NBPS WebService End
			
			if(respStatus1.equalsIgnoreCase("0"))
			{
				m_sStatus = ResourcesUtils.getUnsuccessful ();
				throw IBErrorHandler.createBusinessException ("jomPay.host.error.message.", respErrCode1);
			}
			else
			{
				//Setting input for WebService 2
				channel 			= 	JomPayContants.jomPayWSChannel;//HD
				subChannel 			= 	JomPayContants.jomPayWSSubChannel;//HD
				toAccountNo			=	m_sToAccount;
				amount				= 	m_sAmount;
				chargeAmount		= 	"0";
				toName				= 	merchantName;
				fromName			= 	profile.getAccountName();//acctResp.getAccountNickname();
				rimNo				= 	rimNo;
				paymentDescription	=	"";
				phnxPrincipleDesc  	=	"";
				phnxChargesDesc  	=	"";
				channelRefNo		=	m_sTrnxID;
				paymentType			=	"01";
				accountType 		= 	acctResp.getApplType().equalsIgnoreCase("SV")?"1":"2";
				recipientRefNo		=	ref1;
				recipientRefNo2		=	ref2;
				billerCode			=	merchant;
				paymentChannel		=	JomPayContants.jomPayWSPaymentChannel;//HD//1.InternetBanking|2.ATM|3.MobileBanking|4.MyClearUSSD|5.OverTheCounter
				payerType			=	JomPayContants.jomPayWSPayerType;//HD
				chargesColAccount	=	null;
				jomPayRefNo			=	respJomPayRefNo1;
				
				if(SI_PAYMENT_MODE.RECURRING_PAYMENT.getCode ().equals (siPaymentModeCode)) {
					phnxPrincipleDesc  	=	"IB JP(SI):";
				} else {
					phnxPrincipleDesc  	=	"IB JP(FP):";
				}
				
				phnxPrincipleDesc = phnxPrincipleDesc + (toName.length() > 20?toName.substring(0, 20):toName) + "," + recipientRefNo + "," + jomPayRefNo;
				
	//			Content m_oPayeeContent = new GenericBVDataServicesImpl (m_oSessionObj).getContentListByKey (
	//					table.getStringValue(0, LogTables.IB_BILL_PAYMENT.PAYEE_CODE.toString ()),
	//					BillPaymentContants.TBL_IB_PAYEE_LIST, IBSessionObjects.SERVICE_NAME_VALUE);
	
	//			boolean m_bOnline 	= isTrue (m_oPayeeContent.getStringValue (BillPaymentContants.COL_ONLINE_PAYMENT));
	
				//check daily limit
				Map m_oSILimitMap = IBGenericSIServices.verifySIDailyLimitByBank (p_oEnterpriseServices, null, null,
						m_sSIServiceCode, m_sAmount, m_oDate.getSimpleDate (), true);
	
				//Pixakraft Bank Negara changes 25th Mar 2013
				boolean exceedGlobalLimit = IBGenericPaymentServices.exceedGlobalDailyLimit(p_oEnterpriseServices, m_sAmount, m_sSIServiceCode);
				
				if (!((Boolean) m_oSILimitMap.get (SIConstants.TRANS_STATUS)).booleanValue ())
		        {
					m_boIsResultSuccessful = false;
					m_sStatus = ResourcesUtils.getUnsuccessful ();
					m_sReason = ResourcesUtils.getBusinessExceptionErrorMessage (IBBusinessException.SI,
		            		SIConstants.ERR_BANK_MAX_LIMIT,
		            		new String [] { FormatterUtils.formatMoneyDisplay ( (String)m_oSILimitMap.get (SIConstants.MAX_LIMIT),
		            				fromCurrency, true) });
		        }//Pixakraft Bank Negara changes 25th Mar 2013
				else if(exceedGlobalLimit){
					m_boIsResultSuccessful = false;
					m_sStatus = ResourcesUtils.getUnsuccessful ();
					String globalDailyLimit = IBPaymentUtils.getGlobalLimit(BillPaymentContants.GLOBAL_BILLPAYMENT_DAILY_LIMIT);
					m_sReason = ResourcesUtils.getBusinessExceptionErrorMessage (IBBusinessException.SI, SIConstants.ERR_BANK_GLOBAL_LIMIT,
		            		new String [] { FormatterUtils.formatMoneyDisplay ( globalDailyLimit, fromCurrency, true) });
				}
				else
				{
					GenericESBServicesImpl m_oEsbServices = new GenericESBServicesImpl (m_oSessionObj);
	
					ESBAccountEnquiryTC100Bean m_oTCEnquiryBean = m_oEsbServices.getAccountDetailsTC100 (m_sFromAccount);
					if (!DataValidator.isEmptyString (m_oTCEnquiryBean.getAvailable_Bal ()))
					{
						m_dAvailableBal = Double.parseDouble (m_oTCEnquiryBean.getAvailable_Bal ());
					}
					
					if (SI_PAYMENT_MODE.RECURRING_PAYMENT.getCode ().equals (siPaymentModeCode))
					{
	    				m_dSICharges = IBGenericSIServices.getSICharges (ServiceInfo.SI_FEE_JOMPAY);
		    			m_sSICharges = String.valueOf (m_dSICharges);
	
						//#-- added by pixa 20121017 start --remember to include import at top
		    			onlineAccSIPromoBean = IBUtilsOnlineAcc.getChargesIfIsOnlineAccount(m_oEsbServices,m_sFromAccount, OnlineAccConstants.SI);
		            	if(onlineAccSIPromoBean !=null){
		            		m_sSICharges = onlineAccSIPromoBean.getPromotionCharges();
		            		m_dSICharges = Double.valueOf(m_sSICharges);
		            	}
		            	//#-- added by pixa 20121017 end --
		            	
						if (m_dSICharges > 0)
						{
							if (m_dAvailableBal > m_dSICharges)
							{
								m_sChargeGLAccount = IBGenericSIServices.getSICollectionAccountNo (m_sFromAccount);
	
								ESBTransferToGLBean m_oESBTransferToGLBean = m_oEsbServices.chargesTransfer (m_sFromAccount,
										m_sChargeGLAccount, m_sSICharges, ESBConstants.SI_CHARGES, null, "", "", "", "");
	
								m_sSIChargeResponseCode = m_oESBTransferToGLBean.getResponseCode ();
								if (ESBConstants.IB_SUCCESS_RC.equalsIgnoreCase (m_sSIChargeResponseCode))
								{
									m_boSIChargeStatus = true;
									m_sSIChargesRefNo = m_oESBTransferToGLBean.getReferenceNo ();
								}
								else
								{
									m_boIsFundSufficient = false;
									m_boIsResultSuccessful = false;
									m_sStatus = ResourcesUtils.getUnsuccessful ();
									m_sReason = m_oESBTransferToGLBean.getErrorMessage ();
								}
							}
							else
							{
								m_boIsFundSufficient = false;
								m_boIsResultSuccessful = false;
								m_sStatus = ResourcesUtils.getUnsuccessful ();
								m_sReason = ResourcesUtils.getApplicationResourceMessage (SIConstants.RESOURCES_INSUFFICIENT_FUND);
							}
						}
					}
					
					if (m_boIsFundSufficient)
	    			{
						m_dTransferAmount = Double.parseDouble (m_sAmount);
						m_dTotalAmount = m_dTransferAmount + m_dSICharges;
	
						if(m_dAvailableBal < m_dTotalAmount)
						{
							m_boIsFundSufficient = false;
							m_boIsResultSuccessful = false;
							m_sStatus = ResourcesUtils.getUnsuccessful ();
							m_sTransStatusMsg = ResourcesUtils.getApplicationResourceMessage (SIConstants.RESOURCES_INSUFFICIENT_FUND);
							m_sReason = m_sTransStatusMsg;
						}
	    			}
					
					if (m_boIsFundSufficient)
					{
						//NBPS WebService Start
						xmlResponse = AddIBGNBPSEntry(channel,subChannel,fromAccountNo,toAccountNo,amount,chargeAmount,toName,fromName,rimNo,paymentDescription,phnxChargesDesc,phnxPrincipleDesc,channelRefNo,paymentType,accountType,recipientRefNo,recipientRefNo2,billerCode,paymentChannel,payerType,chargesColAccount,jomPayRefNo);
						readXmlResponse2(xmlResponse);
						
						if(respStatus.equalsIgnoreCase("0"))
						{
							m_sStatus = ResourcesUtils.getUnsuccessful ();
						}
						else if(respStatus.equalsIgnoreCase("1"))
						{
							m_sStatus = ResourcesUtils.getSuccessful();
							m_boIsResultSuccessful = true;
							
							ESBAccountEnquiryTC100Bean m_oTCEnquiryBeanNew = m_oEsbServices.getAccountDetailsTC100 (fromAccountNo);
							m_sAccNewBal = m_oTCEnquiryBeanNew.getAvailable_Bal();
						}
						//NBPS WebService End
					}
	
					//log into si history
	
					if(DataValidator.isEmptyString(m_sToAccount))
					{
						m_sToAccount = "";
					}
				}

				IBLogger.logSIHistory(p_oEnterpriseServices, rimNo, siId, m_sTrnxID, m_oDate.getJavaDate (),
						SIConstants.TRANSCODE_JOMPAY,
						m_sFromAccount, m_sToAccount, fromCurrency, toCurrency,
						m_sAmount,
						"0", // ForeignAmount
						m_sChargesAmount,
						m_sSICharges, // SICharges
						m_sStatus,
						m_sReason,
						respFundReferenceNo, //m_sPhoenixReference
						m_sRevertReference, // PhxRevRefNo
						m_boRevertStatus, // PhxRevStatus
						m_sEPayReference, // EpayRefNo
						"", // PhxChargeRefNo
						true, // PhxChargeStatus
						"", // PhxChargeRevRefNo
						false, // PhxCharRevStatus
						m_sSIChargesRefNo, // SIChargeRefNo
						m_boSIChargeStatus,
						m_sSIChargesRevertRefNo,
						m_boSIChargeRevertStatus,
						m_sSIServiceCode,
						m_boIsResultSuccessful,
						"", //m_sProductCode
						"", //p_sProdSubCode
						merchant,
						m_sMerchantAccNo,
						"", //m_sMerchantId
						"", //m_sOperatorId
						"", //m_sTerminalId
						"", //p_sRespPin
						"", //p_sRespPinExp
						"", //m_sMercRespCode
						"", //m_sMercRespMsg
						"" //m_sTransTraceId
						,"","","",false
						);
				
				//SMS Notification START
				SMSServices.sendCustomerSMSForSI (
						p_oEnterpriseServices, 
						userId, 
						m_sSIServiceCode, 
						SIConstants.TRANSCODE_JOMPAY, 
						m_sStatus, 
						m_sTrnxID, 
						m_sFromAccount, 
						m_sAmount, 
						m_oDate,
						FormatterUtils.formatMoneyDisplay (m_sAccNewBal, "", true),
						merchantName.length()>15?merchantName.substring(0, 15):merchantName);
				//SMS Notification END
			}
			
			IBJomPay ibJomPay = new IBJomPay();
			ibJomPay.setTrxnId(new Long(m_sTrnxID));
			ibJomPay.setAmount(new BigDecimal(m_sAmount));
			ibJomPay.setJomPayRefNo(jomPayRefNo);
			
			HibernateJomPayUtils.updateJomPay(ibJomPay);
			
		} catch (Exception e) {
			e.printStackTrace();
			m_sStatus = ResourcesUtils.getUnsuccessful ();
			if (e instanceof IBGenericException)
			{
				throw (IBGenericException) e;
			}
			throw IBErrorHandler.createServiceException(
					IBServiceException.GENERAL_SERVICE_ERROR, true,
					new String[] {CommonErrorCode.GENERIC_CODE, "", "", "", IBErrorHandler.generateErrorMessage(e)}, c_oClass);
		} finally {
			clearVariables();
		}
		IBLogger.logBSFNMethodLeavingMessage (c_oClass, m_sMethodName, m_oTimer);
	}
	
	public static String AddIBGNBPSEntry(String channel,String subChannel,String fromAccountNo,String toAccountNo,String amount,
										 String chargeAmount,String toName,String fromName,String rimNo,String paymentDescription,
										 String phnxChargesDesc,String phnxPrincipleDesc,String channelRefNo,String paymentType,String accountType,
										 String recipientRefNo,String recipientRefNo2,String billerCode,String paymentChannel,String payerType,
										 String chargeCollectionAccount,String jomPayRefNo) throws Exception
	{	
		StringBuffer XMLEntry = new StringBuffer();
		
		XMLEntry.append("<Msg>");
			XMLEntry.append("<channel>").append(channel).append("</channel>");
			XMLEntry.append("<subChannel>").append(subChannel).append("</subChannel>");
			XMLEntry.append("<fromAccountNo>")		.append(fromAccountNo)		.append("</fromAccountNo>");
			XMLEntry.append("<toAccountNo>")		.append(toAccountNo)		.append("</toAccountNo>");
			XMLEntry.append("<amount>")				.append(amount)				.append("</amount>");
			XMLEntry.append("<chargeAmount>")		.append(chargeAmount)		.append("</chargeAmount>");
			XMLEntry.append("<toName><![CDATA[")	.append(toName)				.append("]]></toName>");
			XMLEntry.append("<fromName><![CDATA[")	.append(fromName)			.append("]]></fromName>");
			XMLEntry.append("<rimNo>")				.append(rimNo)				.append("</rimNo>");
			XMLEntry.append("<paymentDescription><![CDATA[").append(paymentDescription)	.append("]]></paymentDescription>");
			XMLEntry.append("<phnxChargesDesc><![CDATA[")	.append(phnxChargesDesc)	.append("]]></phnxChargesDesc>");
			XMLEntry.append("<phnxPrincipleDesc><![CDATA[")	.append(phnxPrincipleDesc)	.append("]]></phnxPrincipleDesc>");
			XMLEntry.append("<channelRefNo>")		.append(channelRefNo)			.append("</channelRefNo>");
			XMLEntry.append("<paymentType>")		.append(paymentType)		.append("</paymentType>");
			XMLEntry.append("<accountType>")		.append(accountType)		.append("</accountType>");
			XMLEntry.append("<recipientRefNo>")		.append(recipientRefNo)		.append("</recipientRefNo>");
			XMLEntry.append("<recipientRefNo2>")	.append(recipientRefNo2)	.append("</recipientRefNo2>");
			XMLEntry.append("<billerCode>")			.append(billerCode)			.append("</billerCode>");
			XMLEntry.append("<paymentChannel>")		.append(paymentChannel)		.append("</paymentChannel>");
			XMLEntry.append("<payerType>")			.append(payerType)			.append("</payerType>");
			XMLEntry.append("<chargeCollectionAccount>").append(chargeCollectionAccount).append("</chargeCollectionAccount>");
			XMLEntry.append("<jomPayRefNo>")		.append(jomPayRefNo).append("</jomPayRefNo>");
		XMLEntry.append("</Msg>");
			
		System.out.println(XMLEntry);
		
		Properties m_oProp = ESBIntegrationConfig.getInstance ().getprop ();
		NBPSWS1ServiceLocator m_oLocator = new NBPSWS1ServiceLocator();
//		m_oLocator.setkfhwsEndpointAddress("https://10.20.203.12:8443/NBPS/services/kfhws");
		m_oLocator.setkfhwsEndpointAddress(m_oProp.getProperty ("esb.nbps.ws.path"));
		
		NBPSWS1Service m_oService = m_oLocator;
		NBPSWS1 m_oIBG = m_oService.getkfhws();
		String response = m_oIBG.channelToNBPS(XMLEntry.toString());
		
		System.out.println("response : "+response);
		return response;
	}
	
	private static void readXmlResponse2(String xmlResponseDoc)
	{
		Document document;
//		xmlResponseDoc = "<Msg><MsgHeader><respCode>0</respCode><respMsg>IBG_FAILED:INVALID EFFECTIVE DATE</respMsg><ServiceID>101</ServiceID></MsgHeader><MsgBody><Records><Record><chargeReferenceNo></chargeReferenceNo><chargeRespCode></chargeRespCode><oid>20140923007097</oid><fundReferenceNo></fundReferenceNo><fundRespCode></fundRespCode></Record></Records></MsgBody></Msg>";
		try
		{
			document = DocumentHelper.parseText (xmlResponseDoc);
			Element root = document.getRootElement ();
			
			respStatus 				= IBJomPayUtils.replaceNull(root.elementText(JomPayContants.jomPayWSRespStatus));
			respErrCode 			= IBJomPayUtils.replaceNull(root.elementText(JomPayContants.jomPayWSRespErrCode));
			respErrMsg 				= IBJomPayUtils.replaceNull(root.elementText(JomPayContants.jomPayWSRespErrMsg));
			respJomPayRefNo 		= IBJomPayUtils.replaceNull(root.elementText(JomPayContants.jomPayWSRespJomPayRefNo));
			respDateTime 			= IBJomPayUtils.replaceNull(root.elementText(JomPayContants.jomPayWSRespDateTime));
			respChannelRefNo 		= IBJomPayUtils.replaceNull(root.elementText(JomPayContants.jomPayWSRespChannelRefNo));
			respChargeReferenceNo 	= IBJomPayUtils.replaceNull(root.elementText(JomPayContants.jomPayWSRespChargeRefNo));
			respChargeRespCode 		= IBJomPayUtils.replaceNull(root.elementText(JomPayContants.jomPayWSRespChargeRespCode));
			respFundReferenceNo 	= IBJomPayUtils.replaceNull(root.elementText(JomPayContants.jomPayWSRespFundRefNo));
			respFundRespCode 		= IBJomPayUtils.replaceNull(root.elementText(JomPayContants.jomPayWSRespFundRespCode));
		}
		catch (DocumentException e) {
			e.printStackTrace();
		}
	}
	
	public static String kfhWS1(String channel,String subChannel,String amount,
			String channelRefNo,String accountType,String recipientRefNo,
			String recipientRefNo2,String billerCode,String paymentChannel) throws Exception
	{	
		StringBuffer XMLEntry = new StringBuffer();
		
		XMLEntry.append("<Msg>");
		XMLEntry.append("<channel>")			.append(channel)			.append("</channel>");
		XMLEntry.append("<subChannel>")			.append(subChannel)			.append("</subChannel>");
		XMLEntry.append("<amount>")				.append(amount)				.append("</amount>");
		XMLEntry.append("<channelRefNo>")		.append(channelRefNo)		.append("</channelRefNo>");
		XMLEntry.append("<accountType>")		.append(accountType)		.append("</accountType>");
		XMLEntry.append("<recipientRefNo>")		.append(recipientRefNo)		.append("</recipientRefNo>");
		XMLEntry.append("<recipientRefNo2>")	.append(recipientRefNo2)	.append("</recipientRefNo2>");
		XMLEntry.append("<billerCode>")			.append(billerCode)			.append("</billerCode>");
		XMLEntry.append("<paymentChannel>")		.append(paymentChannel)		.append("</paymentChannel>");
		XMLEntry.append("</Msg>");
		
		Properties m_oProp = ESBIntegrationConfig.getInstance ().getprop ();
		NBPSWS1ServiceLocator m_oLocator = new NBPSWS1ServiceLocator();
		m_oLocator.setkfhwsEndpointAddress(m_oProp.getProperty ("esb.nbps.ws.path"));
		
		NBPSWS1Service m_oService = m_oLocator;
		NBPSWS1 m_oIBG = m_oService.getkfhws();
		String response = m_oIBG.NBPSToChannel(XMLEntry.toString());
		
		System.out.println("request :" + XMLEntry.toString());
		System.out.println("response : "+response);
		return response;
	}
	
	public static void readXmlResponse1(String xmlResponseDoc)
	{
		Document document;
		try
		{
			document = DocumentHelper.parseText (xmlResponseDoc);
			Element root = document.getRootElement ();
			
			respStatus1 		= IBJomPayUtils.replaceNull(root.elementText(JomPayContants.jomPayWSRespStatus));
			respErrCode1 		= IBJomPayUtils.replaceNull(root.elementText(JomPayContants.jomPayWSRespErrCode));
			respErrMsg1 		= IBJomPayUtils.replaceNull(root.elementText(JomPayContants.jomPayWSRespErrMsg));
			respJomPayRefNo1 	= IBJomPayUtils.replaceNull(root.elementText(JomPayContants.jomPayWSRespJomPayRefNo));
			respDateTime1 		= IBJomPayUtils.replaceNull(root.elementText(JomPayContants.jomPayWSRespDateTime));
			respRtnRequired1 	= IBJomPayUtils.replaceNull(root.elementText(JomPayContants.jomPayWSRespRtnRequired));
			respRrnDynamic1 	= IBJomPayUtils.replaceNull(root.elementText(JomPayContants.jomPayWSRespRRNDynamic));
			respRrnInfo1 		= IBJomPayUtils.replaceString(IBJomPayUtils.replaceNull(root.elementText(JomPayContants.jomPayWSRespRRNInfo)));
			respBillerName1 	= IBJomPayUtils.replaceNull(root.elementText(JomPayContants.jomPayWSRespBillerName));
			respBillerCode1 	= IBJomPayUtils.replaceNull(root.elementText(JomPayContants.jomPayWSRespBillerCode));
			respBillerCodeName1 = IBJomPayUtils.replaceNull(root.elementText(JomPayContants.jomPayWSRespBillerCodeName));
			respBillerAccount1 	= IBJomPayUtils.replaceNull(root.elementText(JomPayContants.jomPayWSRespBillerAccount));
			respRfiRouteNo1 	= IBJomPayUtils.replaceNull(root.elementText(JomPayContants.jomPayWSRespRfiRouteNo));
			respMsic1 			= IBJomPayUtils.replaceNull(root.elementText(JomPayContants.jomPayWSRespMsic));
			respChannelRefNo1 	= IBJomPayUtils.replaceNull(root.elementText(JomPayContants.jomPayWSRespChannelRefNo));
		}
		catch (DocumentException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * <pre>
	 * If string given is '0' or 'Yes'
	 * return true else false
	 * </pre>
	 *
	 * @param p_sPaymentType String containing type of payment such as 'OPEN'.etc
	 * @return false
	 */
	private static boolean isTrue (String p_sString)
	{
		if (!DataValidator.isEmptyString (p_sString) &&
				(CommonConstants.BV_INT_YES.equals (p_sString) || CommonConstants.BV_STRING_YES.equals (p_sString)))
		{
			return true;
		}

		return false;
	}
	
	private static void clearVariables() {
		xmlResponse 			= null;
		respStatus 				= null;
		respErrCode 			= null;
		respErrMsg 				= null;
		respJomPayRefNo 		= null;
		respDateTime 			= null;
		respChannelRefNo 		= null;
		respChargeReferenceNo 	= null;
		respChargeRespCode 		= null;
		respFundReferenceNo 	= null;
		respFundRespCode 		= null;
	}
}