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

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;

import my.com.kfh.enterprise.services.IBEnterpriseServicesWorkspace;
import my.com.kfh.enterprise.services.IBUtils;
import my.com.kfh.enterprise.services.common.CommonConstants;
import my.com.kfh.enterprise.services.integration.ESBIntegrationConfig;
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.ESBAccountEnquiryTC100Bean;
import my.com.kfh.web.utils.DataValidator;
import my.com.kfh.web.utils.FormatterUtils;
import my.com.kfh.web.utils.IBDynaBean;
import my.com.kfh.web.utils.IBDynaBeanManager;
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.constant.ServiceInfo;

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

import com.kfh.nbps.webservice.NBPSWS1;
import com.kfh.nbps.webservice.NBPSWS1Service;
import com.kfh.nbps.webservice.NBPSWS1ServiceLocator;

public class IBRegisteredJomPayConfirmServices extends IBEnterpriseServicesWorkspace {
	
	private static Class c_oClass = IBRegisteredJomPayConfirmServices.class;
	
	//WebService Response
	String xmlResponse			=	null;
	String respStatus			=	null;
	String respErrCode			=	null;
	String respErrMsg			=	null;
	String respJomPayRefNo		=	null;
	String respDateTime			=	null;
	String respRtnRequired		=	null;
	String respRrnDynamic		=	null;
	String respRrnInfo			=	null;
	String respBillerName		=	null;
	String respBillerCode		=	null;
	String respBillerCodeName	=	null;
	String respBillerAccount	=	null;
	String respRfiRouteNo		=	null;
	String respMsic				=	null;
	String respChannelRefNo		=	null;
	
	public IBRegisteredJomPayConfirmServices(IBSessionObjects m_oIBSessionObjects) {
		super(m_oIBSessionObjects);
	}

	public void execute() throws Exception {
		
		String m_sMethodName = "executeServices";
		IBTimer m_oTimer = IBLogger.logBSFNMethodEnteringMessage (c_oClass, m_sMethodName);
		
		try {
			IBDynaBean viewBean = null;
			IBDynaBean m_oRegisteredJomPayBean = null;
			IBDynaBean m_oAccountFrom = null;
			IBDynaBean m_oServiceInfoBean = null;
			Map<String, IBDynaBean> m_oFromAccountMap = new LinkedHashMap();
			Map<Integer,IBDynaBean> selectedMap = new LinkedHashMap();
			String m_oJomPayDetailAccountIndex = null;
			String accountBalance = "";
			String amount = "";
			Double accumulatedAmount = 0.00;
			Long m_sTrnxId 	= null;
			String m_oMaxTransferLimit = null;
			String m_oMinTransferLimit = null;
			
			//WebService Request
			String wsChannel			=	null;
			String wsSubChannel			=	null;
			String wsAmount				= 	null;
			String wsChannelRefNo		=	null;
			String wsAccountType		=	null;
			String wsRecipientRefNo		=	null;
			String wsRecipientRefNo2	=	null;
			String wsBillerCode			=	null;
			String wsPaymentChannel		=	null;

			viewBean = (IBDynaBean) getIBDynaBean ().get (JomPayContants.jomPayRegisterView);
			selectedMap = (Map<Integer, IBDynaBean>) viewBean.get(JomPayContants.jomPayRegisterViewSelectedMap);
			m_oFromAccountMap = (Map) viewBean.get(JomPayContants.jomPayViewAccountMap);
			m_oServiceInfoBean = (IBDynaBean)viewBean.get (ServiceInfo.SERVICE_INFO_BEAN);
			
//			Account InFO
			m_oAccountFrom = (IBDynaBean)m_oFromAccountMap.get(getIBDynaBean().get(JomPayContants.jomPayRegisterViewAccountIndex).toString());
			m_oJomPayDetailAccountIndex = getIBDynaBean().get(JomPayContants.jomPayRegisterFormAccountIndex).toString();
			ESBAccountEnquiryTC100Bean m_oTCEnquiryBean = getESBServices().getAccountDetailsTC100(m_oJomPayDetailAccountIndex);
			accountBalance = m_oTCEnquiryBean.getAcct_Avail();
			
			m_oMaxTransferLimit = m_oServiceInfoBean.get(ServiceInfo.BEAN_ATT_MAX_LIMIT).toString();
			m_oMinTransferLimit = m_oServiceInfoBean.get(ServiceInfo.BEAN_ATT_MIN_LIMIT).toString();
			
			for(int i=0;i<selectedMap.size();i++)
			{
				m_sTrnxId 	= new Long(IBUtils.getTransactionId (getIBSessionObjects ().getDataManager ()));
				m_oRegisteredJomPayBean = (IBDynaBean) selectedMap.get(i);
				
				m_oRegisteredJomPayBean.set(JomPayContants.jomPayRegisterViewTransId, String.valueOf(m_sTrnxId));
				amount = getIBDynaBean().get(JomPayContants.jomPayRegisterFormAmount + (i+1)).toString();
				
				if(amount.equalsIgnoreCase(""))
				{
					throw IBErrorHandler.createBusinessException ("jomPay.", "error.registered.amount.required");
				}
				else if(!IBJomPayUtils.isNumeric(amount))
				{
					throw IBErrorHandler.createBusinessException ("jomPay.", "error.registered.amount.format");
				}
				else if(Double.parseDouble(amount) < Double.parseDouble(m_oMinTransferLimit))
				{
					String minLimit = FormatterUtils.formatMoneyDisplay(m_oMinTransferLimit,"",false);
					throw IBErrorHandler.createBusinessException ("jomPay.", "error.lesser.amount.arr", new String[] {String.valueOf(i+1)});
				}			
				else if(Double.parseDouble(amount) > Double.parseDouble(m_oMaxTransferLimit))
				{
					String maxLimit = FormatterUtils.formatMoneyDisplay(m_oMaxTransferLimit,"",false);
					throw IBErrorHandler.createBusinessException ("jomPay.", "error.greater.amount.arr", new String[] {String.valueOf(i+1)});
				}
				else
				{
					accumulatedAmount += Double.parseDouble(amount);
					
					if(Double.parseDouble(accountBalance) < accumulatedAmount)
					{
						throw IBErrorHandler.createBusinessException ("jomPay.", "error.registered.accumulated.value",
								new String[] {accountBalance});
					}
					
					m_oRegisteredJomPayBean.set(JomPayContants.jomPayRegisterViewBillRef2, getIBDynaBean ().get("billRefNumber2_" + (i+1)).toString());
					m_oRegisteredJomPayBean.set(JomPayContants.jomPayRegisterViewAmount, getIBDynaBean ().get("amount" + (i+1)).toString());
					m_oRegisteredJomPayBean.set(JomPayContants.jomPayRegisterViewAmountDisplay, FormatterUtils.formatMoneyDisplay (getIBDynaBean ().get("amount" + (i+1)).toString(), null, true));
					
					//Setting input for WebService
					wsChannel 				= 	JomPayContants.jomPayWSChannel;//HD
					wsSubChannel 			= 	JomPayContants.jomPayWSSubChannel;//HD
					wsAmount				=	m_oRegisteredJomPayBean.get(JomPayContants.jomPayRegisterViewAmount).toString();;
					wsChannelRefNo			=	m_oRegisteredJomPayBean.get(JomPayContants.jomPayRegisterViewTransId).toString();
					wsAccountType			=	m_oAccountFrom.get(JomPayContants.jomPayViewAccountApplType).toString().equalsIgnoreCase("SV")?"1":"2";
					wsRecipientRefNo		=	m_oRegisteredJomPayBean.get(JomPayContants.jomPayRegisterViewBillRef1).toString();
					wsRecipientRefNo2		=	m_oRegisteredJomPayBean.get(JomPayContants.jomPayRegisterViewBillRef2).toString();
					wsBillerCode			=	m_oRegisteredJomPayBean.get(JomPayContants.jomPayRegisterViewBillerCode).toString();
					wsPaymentChannel		=	JomPayContants.jomPayWSPaymentChannel;
					
					//NBPS WebService Start
					xmlResponse = kfhWS1(wsChannel,wsSubChannel,wsAmount,wsChannelRefNo,wsAccountType,wsRecipientRefNo,wsRecipientRefNo2,wsBillerCode,wsPaymentChannel);
					readXmlResponse(xmlResponse);
					//NBPS WebService End
					
					if(respStatus.equalsIgnoreCase("0"))
					{
						throw IBErrorHandler.createBusinessException ("jomPay.host.error.message.arr.", respErrCode, new String[] {String.valueOf(i+1)});
					}
					
					m_oRegisteredJomPayBean.set(JomPayContants.jomPayRegisterViewBillerCodeName, respBillerCodeName);
					m_oRegisteredJomPayBean.set(JomPayContants.jomPayRegisterViewBillerCodeNameDisplay, m_oRegisteredJomPayBean.get("billerCode").toString() + "-" + respBillerCodeName);
					m_oRegisteredJomPayBean.set(JomPayContants.jomPayRegisterViewBillerAccount, respBillerAccount);
					m_oRegisteredJomPayBean.set(JomPayContants.jomPayRegisterViewBillRef1Display, m_oRegisteredJomPayBean.get("billRefNumber1").toString() + respRrnInfo);
					
					m_oRegisteredJomPayBean.set(JomPayContants.jomPayRegisterViewJomPayRef, respJomPayRefNo);
					selectedMap.put(i, m_oRegisteredJomPayBean);
				}
			}
			
			viewBean.set(JomPayContants.jomPayRegisterViewSelectedMap, selectedMap);
			getIBDynaBean().set(JomPayContants.jomPayRegisterView, viewBean);
			if (((Boolean) m_oServiceInfoBean.get (ServiceInfo.BEAN_ATT_TAC_REQUIRED)).booleanValue ())
			{
				IBDynaBean m_oSMSViewBean = IBDynaBeanManager.createIBDynaBean (CommonConstants.SMS_VIEW_BEAN, getIBDynaBean ().getActionMapping ());
				m_oSMSViewBean.set(CommonConstants.SERVICE_ATTR, JomPayContants.jomPayRegi);
				m_oSMSViewBean.set(CommonConstants.TYPE_ATTR, CommonConstants.TYPE_TRANS);
				m_oSMSViewBean.set(CommonConstants.AMOUNT, FormatterUtils.formatMoneyDisplay (amount, null, true));
				if(!DataValidator.isEmptyString(respBillerName)){
					m_oSMSViewBean.set(CommonConstants.BENE_NAME, respBillerName.length()>15?respBillerName.substring(0, 15):respBillerName);
				}

				getIBSessionObjects().setHttpSessionAttrObject(CommonConstants.SMS_VIEW_BEAN, m_oSMSViewBean);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			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);
		}
		IBLogger.logBSFNMethodLeavingMessage (c_oClass, m_sMethodName, m_oTimer);
	}
	
	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>");
		
		System.out.println(XMLEntry);
		
		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 void readXmlResponse(String xmlResponseDoc)
	{
		Document document;
		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));
			respRtnRequired 	= IBJomPayUtils.replaceNull(root.elementText(JomPayContants.jomPayWSRespRtnRequired));
			respRrnDynamic 		= IBJomPayUtils.replaceNull(root.elementText(JomPayContants.jomPayWSRespRRNDynamic));
			respRrnInfo 		= IBJomPayUtils.replaceString(IBJomPayUtils.replaceNull(root.elementText(JomPayContants.jomPayWSRespRRNInfo)));
			respBillerName 		= IBJomPayUtils.replaceNull(root.elementText(JomPayContants.jomPayWSRespBillerName));
			respBillerCode 		= IBJomPayUtils.replaceNull(root.elementText(JomPayContants.jomPayWSRespBillerCode));
			respBillerCodeName 	= IBJomPayUtils.replaceNull(root.elementText(JomPayContants.jomPayWSRespBillerCodeName));
			respBillerAccount 	= IBJomPayUtils.replaceNull(root.elementText(JomPayContants.jomPayWSRespBillerAccount));
			respRfiRouteNo 		= IBJomPayUtils.replaceNull(root.elementText(JomPayContants.jomPayWSRespRfiRouteNo));
			respMsic 			= IBJomPayUtils.replaceNull(root.elementText(JomPayContants.jomPayWSRespMsic));
			respChannelRefNo 	= IBJomPayUtils.replaceNull(root.elementText(JomPayContants.jomPayWSRespChannelRefNo));
		}
		catch (DocumentException e) {
			e.printStackTrace();
		}
	}
}
