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

import java.util.List;
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.hibernate.tables.IBJomPayRegistered;
import my.com.kfh.hibernate.utils.HibernateJomPayUtils;
import my.com.kfh.web.utils.DataValidator;
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 IBMaintenanceJomPayConfirmServices extends IBEnterpriseServicesWorkspace {

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

	public IBMaintenanceJomPayConfirmServices(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_oServiceInfoBean = null;
			
			String m_sTrnxID = null;
			String m_oJomPayDetailBillerCode = null;
			String m_oJomPayDetailBillAccHolderName = null;
			String m_oJomPayDetailRef1 = null;
			String m_oJomPayDetailRef2 = null;
			List<IBJomPayRegistered> list = null;
			Long m_sUserId = 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;
			
			IBDynaBean viewBean = (IBDynaBean) getIBDynaBean ().get (JomPayContants.jomPayMaintenanceView);
			m_oServiceInfoBean = (IBDynaBean)viewBean.get (ServiceInfo.SERVICE_INFO_BEAN);
			
			m_sTrnxID = IBUtils.getTransactionId (getIBSessionObjects ().getDataManager ());
			
			m_oJomPayDetailBillerCode = String.valueOf(getIBDynaBean().get(JomPayContants.jomPayFormBillerCode));
			m_oJomPayDetailBillAccHolderName = String.valueOf(getIBDynaBean().get(JomPayContants.jomPayFormBillerHolderName));
			m_oJomPayDetailRef1 = String.valueOf(getIBDynaBean().get(JomPayContants.jomPayFormBillRef1));
			m_oJomPayDetailRef2 = String.valueOf(getIBDynaBean().get(JomPayContants.jomPayFormBillRef2));
			
			Long userId = getIBSessionObjects ().getVisitor ().getId ();
			
			list = HibernateJomPayUtils.getJomPayRegisteredInfo(userId);
			
			m_sUserId = this.getIBSessionObjects ().getVisitor ().getId ();
			
			// Validation on biller code(Biller Code)
			if(!IBJomPayUtils.mod10Check(m_oJomPayDetailBillerCode))
			{
				throw IBErrorHandler.createBusinessException ("jomPay.", "invalid.biller.code");
			}
			
			for(IBJomPayRegistered obj : list)
			{
				if(obj.getUserId() == m_sUserId && obj.getBillerCode().equalsIgnoreCase(m_oJomPayDetailBillerCode) && obj.getBillRefNumber1().equalsIgnoreCase(m_oJomPayDetailRef1))
				{
					throw IBErrorHandler.createBusinessException ("jomPay.", "error.maintenance.data.existed");
				}
			}
			
			//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.SERVICE_ATTR, JomPayContants.jomPayRegA);
				m_oSMSViewBean.set(CommonConstants.TYPE_ATTR, CommonConstants.TYPE_REQ);
				if(!DataValidator.isEmptyString(respBillerName)){
					m_oSMSViewBean.set(CommonConstants.BENE_NAME, respBillerName.length()>25?respBillerName.substring(0, 25):respBillerName);
				}

				getIBSessionObjects().setHttpSessionAttrObject(CommonConstants.SMS_VIEW_BEAN, m_oSMSViewBean);
			}
			//Pixakarft Bank Negara Changes 30th Mar 2013 start
			
			//Setting input for WebService
			wsChannel 				= 	JomPayContants.jomPayWSChannel;//HD
			wsSubChannel 			= 	JomPayContants.jomPayWSSubChannel;//HD
			wsAmount				=	"1";
			wsChannelRefNo			=	m_sTrnxID;
			wsAccountType			=	"1";
			wsRecipientRefNo		=	m_oJomPayDetailRef1;
			wsRecipientRefNo2		=	m_oJomPayDetailRef2;
			wsBillerCode			=	m_oJomPayDetailBillerCode;
			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.", respErrCode);
			}
			
			viewBean.set(JomPayContants.jomPayViewTransID, m_sTrnxID);
			viewBean.set(JomPayContants.jomPayFormBillerCode, m_oJomPayDetailBillerCode);
			viewBean.set(JomPayContants.jomPayFormBillerHolderName, m_oJomPayDetailBillAccHolderName);
			viewBean.set(JomPayContants.jomPayFormBillRef1, m_oJomPayDetailRef1);
			viewBean.set(JomPayContants.jomPayFormBillRef2, m_oJomPayDetailRef2);
			
			getIBDynaBean().set(JomPayContants.jomPayMaintenanceView, 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>");
		
		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();
		}
	}
}
