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.ib112_si.IBGenericSIServices;
import my.com.kfh.enterprise.services.ib112_si.SIConstants;
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.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 IBOpenJomPayConfirmServices extends IBEnterpriseServicesWorkspace {

	private static Class c_oClass = IBOpenJomPayConfirmServices.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 IBOpenJomPayConfirmServices(IBSessionObjects m_oIBSessionObjects) {
		super(m_oIBSessionObjects);
	}

	public IBOpenJomPayConfirmServices(IBSessionObjects m_oIBSessionObjects,
			String p_sUsername, String p_sPassword) {
		super(m_oIBSessionObjects, p_sUsername, p_sPassword);
	}
	
	public void execute() throws Exception {
		
		String m_sMethodName = "executeServices";
		IBTimer m_oTimer = IBLogger.logBSFNMethodEnteringMessage (c_oClass, m_sMethodName);
		
		try {
			IBDynaBean m_oAccountFrom = null;
			IBDynaBean m_oServiceInfoBean = null;
			Map<String, IBDynaBean> m_oFromAccountMap = new LinkedHashMap();
			String m_oJomPayDetailAccountIndex = null;
			String m_oJomPayDetailBalance = null;
			String m_oJomPayDetailAmount = null;
			String m_oJomPayDetailAmountDisplay = null;
			String m_oJomPayDetailBillerCode = null;
			String m_oJomPayDetailRef1 = null;
			String m_oJomPayDetailRef2 = null;
			String m_oJomPayPayMode = null;
			String m_oJomPayPayModeDisplay = null;
			String m_oJomPayStartDate = null;
			String m_oJomPayEndDate = null;
			Long m_sTrnxId 	= null;
            
            String m_oMaxTransferLimit = null;
            String m_oMinTransferLimit = null;
            
			//WebService Request
			String channel			=	null;
			String subChannel		=	null;
			String amount			= 	null;
			String channelRefNo		=	null;
			String accountType		=	null;
			String recipientRefNo	=	null;
			String recipientRefNo2	=	null;
			String billerCode		=	null;
			String paymentChannel	=	null;
			
			IBDynaBean viewBean = (IBDynaBean) getIBDynaBean ().get (JomPayContants.jomPayOpenView);
			m_oFromAccountMap = (Map) viewBean.get(JomPayContants.jomPayViewAccountMap);
			
			m_oServiceInfoBean = (IBDynaBean)viewBean.get (ServiceInfo.SERVICE_INFO_BEAN);
			
			// Get From Account
			m_oAccountFrom = (IBDynaBean)m_oFromAccountMap.get(getIBDynaBean().get(JomPayContants.jomPayOpenFormAccountIndex).toString());
			m_oJomPayDetailAccountIndex = getIBDynaBean().get(JomPayContants.jomPayOpenFormAccountIndex).toString();
			
			// Account Amount Available
			ESBAccountEnquiryTC100Bean m_oTCEnquiryBean = getESBServices().getAccountDetailsTC100(m_oJomPayDetailAccountIndex);
			
			m_sTrnxId 	= new Long(IBUtils.getTransactionId (getIBSessionObjects ().getDataManager ()));
			m_oJomPayDetailBalance = String.valueOf(m_oTCEnquiryBean.getAcct_Avail());
			m_oJomPayDetailAmount = String.valueOf(getIBDynaBean().get(JomPayContants.jomPayOpenFormAmount));
			m_oJomPayDetailAmountDisplay = FormatterUtils.formatMoneyDisplay (m_oJomPayDetailAmount, null, true);
			m_oJomPayDetailBillerCode = String.valueOf(getIBDynaBean().get(JomPayContants.jomPayOpenFormBillerCode));
			m_oJomPayDetailRef1 = String.valueOf(getIBDynaBean().get(JomPayContants.jomPayOpenFormRef1));
			m_oJomPayDetailRef2 = String.valueOf(getIBDynaBean().get(JomPayContants.jomPayOpenFormRef2));
			m_oJomPayPayMode = String.valueOf(getIBDynaBean().get(SIConstants.PAY_MODE));
            
            m_oMaxTransferLimit = m_oServiceInfoBean.get(ServiceInfo.BEAN_ATT_MAX_LIMIT).toString();
            m_oMinTransferLimit = m_oServiceInfoBean.get(ServiceInfo.BEAN_ATT_MIN_LIMIT).toString();
			
			if(m_oJomPayPayMode.equalsIgnoreCase("01"))
			{
				m_oJomPayPayModeDisplay = "Pay Now";
				m_oJomPayStartDate = "Today";
			}
			else if(m_oJomPayPayMode.equalsIgnoreCase("02"))
			{
				m_oJomPayPayModeDisplay = "Pay Later";
				m_oJomPayStartDate = getIBDynaBean().get(JomPayContants.jomPayOpenFormEffectiveDate).toString();
			}
			else if(m_oJomPayPayMode.equalsIgnoreCase("03"))
			{
				m_oJomPayPayModeDisplay = "Recurring Payment(SI)";
				m_oJomPayStartDate = getIBDynaBean().get(JomPayContants.jomPayOpenFormEffectiveDateRecurring).toString();
				m_oJomPayEndDate = getIBDynaBean().get(JomPayContants.jomPayOpenFormTerminationDate).toString();
			}
			
			// Validation on insufficient amount
			if(Double.parseDouble(m_oJomPayDetailBalance) < Double.parseDouble(m_oJomPayDetailAmount))
			{
				String acctAvail = FormatterUtils.formatMoneyDisplay(m_oJomPayDetailBalance,"",false);
				throw IBErrorHandler.createBusinessException ("jomPay.", "error.insufficient.amount",
								new String[] {acctAvail});
			}
            
            // Validation on Minimum transfer limit
            if(Double.parseDouble(m_oJomPayDetailAmount) < Double.parseDouble(m_oMinTransferLimit))
            {
                String minLimit = FormatterUtils.formatMoneyDisplay(m_oMinTransferLimit,"",false);
                throw IBErrorHandler.createBusinessException ("jomPay.", "error.lesser.amount",
                                                              new String[] {minLimit});
            }
            
            // Validation on Maximum transfer limit
            if(Double.parseDouble(m_oJomPayDetailAmount) > Double.parseDouble(m_oMaxTransferLimit))
            {
                String maxLimit = FormatterUtils.formatMoneyDisplay(m_oMaxTransferLimit,"",false);
                throw IBErrorHandler.createBusinessException ("jomPay.", "error.greater.amount",
                                                              new String[] {maxLimit});
            }
            
            // Validation on biller code(Mod10)
			if(!IBJomPayUtils.mod10Check(m_oJomPayDetailBillerCode))
			{
				throw IBErrorHandler.createBusinessException ("jomPay.", "invalid.biller.code");
			}
			
			//Pixakarft Bank Negara Changes 30th Mar 2013 start
			if (((Boolean) m_oServiceInfoBean.get (ServiceInfo.BEAN_ATT_TAC_REQUIRED)).booleanValue ())
			{
				IBDynaBean m_oSMSViewBean = (IBDynaBean) getIBSessionObjects().getHttpSessionAttrObject(CommonConstants.SMS_VIEW_BEAN);
				m_oSMSViewBean.set(CommonConstants.AMOUNT, m_oJomPayDetailAmountDisplay);
				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);
			}
			//Pixakarft Bank Negara Changes 30th Mar 2013 start
			
			viewBean.set(JomPayContants.jomPayOpenViewTransID, String.valueOf(m_sTrnxId));
			
			//Setting input for WebService
			channel 			= 	JomPayContants.jomPayWSChannel;//HD
			subChannel 			= 	JomPayContants.jomPayWSSubChannel;//HD
			amount				=	m_oJomPayDetailAmount;
			channelRefNo		=	String.valueOf(m_sTrnxId);
			accountType			=	m_oAccountFrom.get("applType").toString().equalsIgnoreCase("SV")?"1":"2";
			recipientRefNo		=	m_oJomPayDetailRef1;
			recipientRefNo2		=	m_oJomPayDetailRef2;
			billerCode			=	m_oJomPayDetailBillerCode;
			paymentChannel		=	JomPayContants.jomPayWSPaymentChannel;
			
			//NBPS WebService Start
			xmlResponse = kfhWS1(channel,subChannel,amount,channelRefNo,accountType,recipientRefNo,recipientRefNo2,billerCode,paymentChannel);
			readXmlResponse(xmlResponse);
			//NBPS WebService End
			
			if(respStatus.equalsIgnoreCase("0"))
			{
				throw IBErrorHandler.createBusinessException ("jomPay.host.error.message.", respErrCode);
			}
			else
			{
				if (m_oServiceInfoBean != null &&
						((Boolean)m_oServiceInfoBean.get (ServiceInfo.BEAN_ATT_FUTURE_TRANSACTION_FLAG)).booleanValue ())
				{
					IBGenericSIServices m_oGenericSIServices = new IBGenericSIServices (getIBSessionObjects ());
					m_oGenericSIServices.setIBDynaBean (getIBDynaBean ());
					m_oGenericSIServices.confirmSIInput (viewBean);
				}
				
				viewBean.set(JomPayContants.jomPayOpenViewAccountIndex, m_oAccountFrom.get("accountNickname") + "-" + m_oAccountFrom.get("accountNo"));
				viewBean.set(JomPayContants.jomPayOpenViewAmount, m_oJomPayDetailAmount);
                viewBean.set(JomPayContants.jomPayOpenViewAmountDisplay, m_oJomPayDetailAmountDisplay);
				viewBean.set(JomPayContants.jomPayOpenViewBillerCode, m_oJomPayDetailBillerCode);
				viewBean.set(JomPayContants.jomPayOpenViewBillerCodeName, respBillerCodeName);
				viewBean.set(JomPayContants.jomPayOpenViewBillerCodeNameDisplay,m_oJomPayDetailBillerCode + "-" + respBillerCodeName);
				viewBean.set(JomPayContants.jomPayOpenBillerAccount, respBillerAccount);
				viewBean.set(JomPayContants.jomPayOpenViewRef1, m_oJomPayDetailRef1);
				viewBean.set(JomPayContants.jomPayOpenViewRef1Display, m_oJomPayDetailRef1 + respRrnInfo);
				viewBean.set(JomPayContants.jomPayOpenViewRef2, m_oJomPayDetailRef2);
				viewBean.set(JomPayContants.jomPayOpenViewJomPayRef, respJomPayRefNo);
				viewBean.set(JomPayContants.jomPayOpenViewPayModeDisplay, m_oJomPayPayModeDisplay);
				viewBean.set(JomPayContants.jomPayOpenViewEffectiveDateDisplay, m_oJomPayStartDate);
				viewBean.set(JomPayContants.jomPayOpenViewTerminateDateDisplay, m_oJomPayEndDate);
				
				getIBDynaBean().set(JomPayContants.jomPayOpenView, viewBean);
			}
		} 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>");
		
		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();
		}
	}
}
