
package my.com.kfh.enterprise.services.ib115_gold.gold_thirdparty;

/**
 * PROGRAMMER: Goh Kee Kun
 * COMPANY: Pixakraft
 * DATE CREATED: 15-Oct-2012
 */

import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import my.com.kfh.enterprise.services.IBUtils;
import my.com.kfh.enterprise.services.IBUtilsExtension;
import my.com.kfh.enterprise.services.common.CommonConstants;
import my.com.kfh.enterprise.services.ib101_access.AccessConstants;
import my.com.kfh.enterprise.services.ib106_utility.UtilityConstants;
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.SI_PAYMENT_MODE;
import my.com.kfh.enterprise.services.ib115_gold.IBGenericGoldServices;
import my.com.kfh.enterprise.services.ib115_gold.constant.GoldConstants;
import my.com.kfh.enterprise.services.ib115_gold.constant.SIConstantsExtension;
import my.com.kfh.enterprise.services.integration.ESBAccountBalanceServices;
import my.com.kfh.enterprise.services.integration.ESBPhoenixWSServices;
import my.com.kfh.enterprise.services.integration.ESBProcessBean;
import my.com.kfh.enterprise.services.integration.ESBProcessBeanInterface;
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.agent.ESBXapi905Agent;
import my.com.kfh.esb.constant.EnumAccType;
import my.com.kfh.esb.constant.EnumApplType;
import my.com.kfh.esb.constant.EnumDepLoan;
import my.com.kfh.esb.constant.EnumPhoenixTranCode;
import my.com.kfh.esb.request.ESBRequestAccountBalanceBean;
import my.com.kfh.esb.request.ESBRequestPhoenixWSBean;
import my.com.kfh.esb.request.ESBRequestXapi905Bean;
import my.com.kfh.esb.response.ESBAccCreateDateBean;
import my.com.kfh.esb.response.ESBAccountBalanceBean;
import my.com.kfh.esb.response.ESBAccountDetailsBean;
import my.com.kfh.esb.response.ESBMsgHeader;
import my.com.kfh.esb.response.ESBResponseXapi905Bean;
import my.com.kfh.sms.services.SMSConstants;
import my.com.kfh.sms.services.SMSServices;
import my.com.kfh.web.utils.BVI_DateTime;
import my.com.kfh.web.utils.DataUtils;
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.IBDynaBeanManager;
import my.com.kfh.web.utils.IBLogWriter;
import my.com.kfh.web.utils.IBLogger;
import my.com.kfh.web.utils.IBLoggerExtension;
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.ServiceInfo;

import org.dom4j.Document;
import org.dom4j.Element;


/**
 * Send transfer details to host to perform favourite Intrabank transfer.
 */
public class IBGoldReg3rdPartyTransferResultsServices extends IBGenericGoldServices
{
	private static Class c_oClass = IBGoldReg3rdPartyTransferResultsServices.class;

	private static String FAV_VIEWBEAN = ThirdPartyGoldTransferTags.REG_THIRDPARTY_GOLD_TRANSFER_VIEW;

	/**
	 * Class constructor specifying session object.
	 *
	 * @param m_oIBSessionObjects session object containing all information stored in HTTP session
	 */
	public IBGoldReg3rdPartyTransferResultsServices (IBSessionObjects m_oIBSessionObjects)
	{
		super (m_oIBSessionObjects);
	}

	/**
     * Verify TAC and verify amount against maximum limit for transfer.<BR>
     * Perform transfer to host.<BR>
     * If transaction is successful, create transfer receipt and if schedule date is today, send email to recipient.<BR>
     * Then, logs transaction details.
	 *
	 * @throws IBGenericException if any Exception are thrown
	 */
	public void processTransferResult () throws IBGenericException
	{
		String m_sMethodName = "processTransferResult";
		IBTimer m_oTimer = IBLogger.logBSFNMethodEnteringMessage (c_oClass, m_sMethodName);

		IBDynaBean m_oViewBean = null;
		IBDynaBean m_oServiceInfoBean = null;
		BVI_DateTime m_oCurrentBVIDateTime = null;
//		ESBThirdFundTransferBean m_oReturnedESBBean = new ESBThirdFundTransferBean ();
		String m_sTransStatus = ResourcesUtils.getUnsuccessful ();
		String m_sTransStatusMsg = "";
		String m_sFromAccount = "";
		String m_sToRegAccount = "";
		String m_sAmount = "0";
		String m_sAmountDis = "";
		String m_sLocalAmountStr = "";
		String m_sAccountHolderName = "";
        String m_sEmail = "";
		String m_sUserTransferRef = "";
        String m_sHostRefNo = "";
        String m_sPhx_Ref_no = "";
		String m_sNewBalance = "";
		String m_sTransId = "";
		String m_sFormattedTransId = "";
//        String m_sServiceMaxLimit = "";
//        String m_sFromIsoCurrency = CurrencyCode.MALAYSIA_RINGGIT; //default to MYR
//        String m_sToIsoCurrency = CurrencyCode.MALAYSIA_RINGGIT; //default to MYR
        String m_sFromIsoCurrency = GoldConstants.GOLD_CURRENCY; //default to XAU
        String m_sToIsoCurrency = GoldConstants.GOLD_CURRENCY; //default to XAU
//        String m_sResponseCode = "";
        String m_sServiceCode = "";
        String m_sServiceName = "";
        String m_sFrmAccCrtDt = "";
        String m_sToAccCrtDt = "";
		boolean m_boIsResultSuccessful = false;
		boolean m_boToDisplayNewBal = false;
//		Float m_fUserLimit = null;

//      si
		Date m_oEffectiveDate = null;
		boolean m_boSIIndicator = false;
		boolean m_boDeleteSIIndicator = false;
		String m_sEffectiveDate = null;
		String m_sPaymentFrequencyDisplay = null;
		String m_sPayFrequency = null;
		String m_sTerminationDate = null;
		String m_sPaymentMode = null;
		String m_sPaymentModeDisplay = null;
		String m_sEffectiveDateDisplay = null;
		String m_sTerminationDateDisplay = null;
		ESBAccountDetailsBean m_oFromGoldEnquiryBean=null;
//		ESBAccountDetailsBean m_oToAccEnquiryBean=null;
		String m_sFromAccBranchCode=null;
		String m_sFromAccBranchName=null;
		String m_sRimNo = (String)getIBSessionObjects ().getHttpSessionAttrObject (AccessConstants.RIM_NO);
		String m_sCustomerName = getIBSessionObjects ().getVisitor ().getStringValue (AccessConstants.VISITOR_LAST_NAME);


		Map<String, String> m_oReceiptMap = new LinkedHashMap<String, String> ();

		double m_dAvailableBal = 0.0;
		double m_dTotalTransferAmount = 0.0;
		boolean m_boIsFundSufficient = true;
		String m_sSIServiceCode = ThirdPartyGoldTransferTags.GOLDSIFAVT;//ServiceInfo.SI_INTRA_FAV_LIMIT;
//		String m_sSIServiceMaxLimit = null;
//		IBDynaBean m_oSIServiceInfoBean = null;
		boolean m_boIsScheduler = false;
		String isStaff="";

		try
		{
			m_oViewBean = (IBDynaBean) getIBDynaBean ().get (FAV_VIEWBEAN) == null
				? IBDynaBeanManager.createIBDynaBean (FAV_VIEWBEAN, getIBDynaBean ().getActionMapping ())
						:(IBDynaBean) getIBDynaBean ().get (FAV_VIEWBEAN);

			if (m_oViewBean != null)
			{
				m_oServiceInfoBean = (IBDynaBean) m_oViewBean.get (ThirdPartyGoldTransferTags.SERVICE_INFO_BEAN_EXTEND);
			}

			m_oCurrentBVIDateTime = DateTimeUtils.getCurrentIBDateTimeObject ();
			m_oEffectiveDate = m_oCurrentBVIDateTime.getJavaDate ();

			if (m_oServiceInfoBean != null)
			{
				/*
				 * UPASS Verify TAC
				 */
				if (((Boolean)m_oServiceInfoBean.get (ServiceInfo.BEAN_ATT_TAC_REQUIRED)).booleanValue ())
				{
					getIBAuthenticationServices ().userVerifyTac ((String)getIBDynaBean ().get (UtilityConstants.TAC_VALUE),getIBSessionObjects().getIBSessionId());
				}

				m_sServiceCode = (String) m_oServiceInfoBean.get (ServiceInfo.BEAN_ATT_SERVICE_CODE);
                m_sServiceName = (String) m_oServiceInfoBean.get (ServiceInfo.BEAN_ATT_SERVICE_NAME);

				/*
				 * get max limit if not empty
				 */
                //no used
//				if (!DataValidator.isEmptyString ((String) m_oServiceInfoBean.get (ServiceInfo.BEAN_ATT_MAX_LIMIT)))
//				{
//					m_sServiceMaxLimit = (String) m_oServiceInfoBean.get (ServiceInfo.BEAN_ATT_MAX_LIMIT);
//				}
			}

			m_sPaymentMode = (String)getIBDynaBean ().get (SIConstants.PAY_MODE);
			m_sPaymentModeDisplay = (String)m_oViewBean.get (SIConstants.PAY_MODE_DISPLAY);
			m_sEffectiveDateDisplay = (String)m_oViewBean.get (SIConstants.EFFECTIVE_DATE_DISPLAY);

			if (!SI_PAYMENT_MODE.PAY_NOW.getCode ().equals (m_sPaymentMode))
			{
				m_boSIIndicator = true;
				m_sServiceName = IBGenericSIServices.getSITransType (m_sServiceName, m_sPaymentMode);

				m_sEffectiveDate = (String)m_oViewBean.get (SIConstants.EFFECTIVE_DATE_FORMAT);
				BVI_DateTime m_oIbEffectiveDateTime = new BVI_DateTime (m_sEffectiveDate);
				m_oEffectiveDate = m_oIbEffectiveDateTime.getJavaDate ();

				if (SI_PAYMENT_MODE.RECURRING_PAYMENT.getCode ().equals (m_sPaymentMode))
				{
					m_sPayFrequency = (String)getIBDynaBean ().get (SIConstants.PAY_FREQUENCY);
					m_sPaymentFrequencyDisplay = (String)m_oViewBean.get (SIConstants.PAY_FREQUENCY_DISPLAY);
					m_sTerminationDate = (String) m_oViewBean.get (SIConstants.TERMINATION_DATE_FORMAT);
					m_sTerminationDateDisplay = (String)m_oViewBean.get (SIConstants.TERMINATION_DATE_DISPLAY);
				}
			}

			m_sEffectiveDate = DateTimeUtils.formatIBDateTimeToYMD (m_oEffectiveDate);
			m_sFromAccount = (String) getIBDynaBean ().get (ThirdPartyGoldTransferTags.FROM_ACCOUNT);
			isStaff = (ESBConstants.ACC_STAFF.equalsIgnoreCase(getESBServices().getInquiryStaffByAcctNo(m_sFromAccount).getStatus()))?"Y":"N";
			m_sToRegAccount = (String) getIBDynaBean ().get (ThirdPartyGoldTransferTags.TO_REG_ACCOUNT);
			m_sAmount = (String) getIBDynaBean ().get (ThirdPartyGoldTransferTags.AMOUNT);
			m_sUserTransferRef = (String) getIBDynaBean ().get (ThirdPartyGoldTransferTags.TRANSFER_REF);
            m_sEmail = (String) getIBDynaBean ().get (ThirdPartyGoldTransferTags.EMAIL);
            m_sFromIsoCurrency = (String) m_oViewBean.get (ThirdPartyGoldTransferTags.FROM_ISO_CURRENCY);
            m_sToIsoCurrency = (String) m_oViewBean.get (ThirdPartyGoldTransferTags.TO_ISO_CURRENCY);
            m_sAmountDis = (String) m_oViewBean.get (ThirdPartyGoldTransferTags.AMOUNT_DIS);
            m_sAccountHolderName = (String) m_oViewBean.get (ThirdPartyGoldTransferTags.ACCOUNT_HOLDER_NAME);

			/*
			 * get transaction ID
			 */
	        m_sTransId = IBUtils.getTransactionId (getIBSessionObjects ().getDataManager ());
	        m_sFormattedTransId = FormatterUtils.formatTransID (m_sTransId);

            /*
             * convert amount to local (RM)
             */
//            m_sLocalAmountStr = IBGoldTransferDBUtils.getLocalAmount (this, m_sToIsoCurrency, m_sAmount, m_oServiceInfoBean);
            m_sLocalAmountStr = m_sAmount;
            if (SI_PAYMENT_MODE.PAY_NOW.getCode ().equals (m_sPaymentMode))
            {
	            /*
	             * check limit againts total amount per day
	             */
		        Map m_oBankLimitReturnMap = IBGold3rdPartyTransferBaseServices.checkIntraTransferDailyLimit (this,
	            		getIBDynaBean (), getIBSessionObjects (), m_sLocalAmountStr, m_sEffectiveDate, m_boSIIndicator, m_boIsScheduler);

//				m_fUserLimit = IBGoldTransferDBUtils.getUserTransferLimit (getIBSessionObjects (), m_sServiceCode, m_boIsScheduler);
//
//				Map m_oUserLimitReturnMap = IBGold3rdPartyTransferBaseServices.checkIntraTransferDailyLimitByServiceCode (this,
//						m_sLocalAmountStr, m_sServiceMaxLimit, m_fUserLimit, m_sServiceCode, m_sEffectiveDate, m_boSIIndicator, m_boIsScheduler);

				if (!((Boolean) m_oBankLimitReturnMap.get (ThirdPartyGoldTransferTags.STATUS)).booleanValue ())
	            {
	            	m_boIsResultSuccessful = false;

	                m_sTransStatus = ResourcesUtils.getUnsuccessful ();
	                m_sTransStatusMsg = ResourcesUtils.getApplicationResourceMessage (ThirdPartyGoldTransferTags.ERR_BANK_MAX_AMOUNT,
	                		new String [] { FormatterUtils.formatGoldUnitDisplay ((String) m_oBankLimitReturnMap.get (ThirdPartyGoldTransferTags.MAX_LIMIT), true) });
	            } 
//	            else if (!((Boolean) m_oUserLimitReturnMap.get (ThirdPartyGoldTransferTags.STATUS)).booleanValue ())
//				{
//	            	m_boIsResultSuccessful = false;
//
//					m_sTransStatus = ResourcesUtils.getUnsuccessful ();
//					m_sTransStatusMsg = ResourcesUtils.getApplicationResourceMessage (ThirdPartyGoldTransferTags.ERR_MAX_AMOUNT,
//							new String [] { FormatterUtils.formatMoneyDisplay ((String) m_oUserLimitReturnMap.get (ThirdPartyGoldTransferTags.MAX_LIMIT),
//									CurrencyCode.MALAYSIA_RINGGIT, true) });
//				}
	            else
	            {
	            	m_oFromGoldEnquiryBean = getESBServices().getAccountDetails (m_sFromAccount);
					
//					ESBAccountEnquiryTC100Bean m_oTCEnquiryBean = getESBServices ().getAccountDetailsTC100 (m_sFromAccount);
					if (!DataValidator.isEmptyString (m_oFromGoldEnquiryBean.getAvailableBalance ()))
					{
						m_dAvailableBal = Double.parseDouble (m_oFromGoldEnquiryBean.getAvailableBalance ());
					}

					
					m_dTotalTransferAmount = Double.parseDouble (m_sAmount);

					if(m_dAvailableBal < m_dTotalTransferAmount)
					{
						m_boIsFundSufficient = false;
						m_boIsResultSuccessful = false;
						m_sTransStatus = ResourcesUtils.getUnsuccessful ();
						m_sTransStatusMsg = ResourcesUtils.getApplicationResourceMessage (ThirdPartyGoldTransferTags.INSUFFICIENT_GOLD);
					}

					if (m_boIsFundSufficient)
					{
						/*
		            	 * do transfer
		            	 */
						try
						{
							m_sRimNo = (String)getIBSessionObjects ().getHttpSessionAttrObject (AccessConstants.RIM_NO);
							
							if(!DataValidator.isEmptyString(m_sFromAccount))
								m_sFromAccBranchCode=super.getBranchCodeByAccNo(m_sFromAccount); 			
							if (!DataValidator.isEmptyString (m_sFromAccBranchCode))
							{
								m_sFromAccBranchName=IBUtilsExtension.getGoldBranchNameByBranchCode(this, m_sFromAccBranchCode);
							}
		    				
		    				Map<String,ESBProcessBeanInterface> tranSet=new HashMap<String,ESBProcessBeanInterface>();
		    				
		    				
		    				ESBRequestXapi905Bean tranSetFirst=new ESBRequestXapi905Bean(m_oFromGoldEnquiryBean,
		    						EnumApplType.CK, EnumAccType.CK_GOLD, m_sToRegAccount,
		    						m_sAmount, null, ThirdPartyGoldTransferTags.GOLD_TRANSFER_3RD, EnumPhoenixTranCode.TRANSFER_WITHDRAWAL ,
		    						m_sFromAccBranchCode, EnumDepLoan.DEP_DP,"",m_sRimNo);
		    				
		    				
		    				ESBXapi905Agent agent1=new ESBXapi905Agent(tranSetFirst);
		    				
		    				tranSet.put("1", agent1);

		    				Map<String, Document> responseMap=getEsbServiceFactory().implementService(tranSet);
		            		
		    				ESBResponseXapi905Bean responseBean905=null;
							boolean isSuccess=false;
							ESBMsgHeader msgResponse=new ESBMsgHeader();
							
							
							for (String mapKey : responseMap.keySet()) {
								Document doc=responseMap.get(mapKey);
								if(doc != null){
									// *** start querying the response code from DOCMENT of transet ***
									Element root = doc.getRootElement ();
									msgResponse = new ESBProcessBean().processResponseCode(root);
									Element msgHeader = root.element ("MsgHeader");
									m_sPhx_Ref_no = (msgHeader.elementText ("ReferenceNo"));
									String code=mapKey.substring(mapKey.length()-2, mapKey.length());
									String key=mapKey.substring(0, mapKey.length()-2);	
									
									if(code.equalsIgnoreCase(GoldConstants.ESB_TRANS_SUCCESS) 
											&& ESBConstants.IB_SUCCESS_RC.equalsIgnoreCase(msgResponse.getResponseCode())){
										if(key.equalsIgnoreCase("1")){
											agent1.setDocument(doc);
											responseBean905=agent1.getResponsebean();
										}
										isSuccess=true;
									}else{
										//"*** failed response code **
										isSuccess=false;
										msgResponse.setResponseCode (ESBProcessBean.ESB_FAIL_CODE);
										msgResponse.setErrorMessage (ResourcesUtils.getServiceExceptionErrorKey ("esb.error.phx.PHX-",msgResponse.getResponseCode ()));
										break;
									}
								}else {
									//*** Document is null
									msgResponse.setResponseCode (ESBProcessBean.ESB_FAIL_CODE);
									msgResponse.setErrorMessage (ResourcesUtils.getServiceExceptionErrorKey ("esb.error.phx.PHX-",msgResponse.getResponseCode ()));						
									isSuccess=false;
									break;
								}						
								//!!! Response Code query ended !!!			
							}
		    				
		    				
		    				
		    				
		    				
//							m_oReturnedESBBean = getESBServices ().intrabankFundTransfer (
//									m_sFromAccount, m_sToRegAccount, ESBConstants.FUND_TRANSFER_3RD, m_sAmount, m_sEffectiveDate);

							
							if (isSuccess)
							{
								m_sTransStatus = ResourcesUtils.getSuccessful ();
								m_boIsResultSuccessful = true;
								m_boToDisplayNewBal = true;
								
								ESBRequestAccountBalanceBean m_oBeanReq = new ESBRequestAccountBalanceBean ();
								ESBAccountBalanceServices m_oService = new ESBAccountBalanceServices ();
								ESBAccountBalanceBean m_oBeanResp = null;
								
								// From Account Balance
								m_oBeanReq.setAccountNo (m_oFromGoldEnquiryBean.getAccountNo()); // get gold account no
								m_oBeanReq.setRimNo (m_sRimNo); // get gold account rim no
								m_oBeanResp = m_oService.retrieve (m_oBeanReq);
								responseBean905.setFromAccountNewBalance (m_oBeanResp.getCurrentBalance());// get new gram balance
								m_sNewBalance = m_oBeanResp.getAvailableBalance();

								 m_sHostRefNo = responseBean905.getTransactionReference ().trim ();
//								 m_sResponseCode = responseBean905.getResponseCode ().trim ();

//								 m_sNewBalance = FormatterUtils.formatMoneyDisplay (
//										 DataValidator.isEmptyString (m_oReturnedESBBean.getFromAccountBalance ().trim ()) ? "0"
//		 										: m_oReturnedESBBean.getFromAccountBalance ().trim (),
//												 m_sFromIsoCurrency, true);
								 
								//Account Creation Date
									ESBPhoenixWSServices mService = new ESBPhoenixWSServices();
									ESBRequestPhoenixWSBean m_oRequest = new ESBRequestPhoenixWSBean();

									// From Account Creation Date
									m_oRequest.setAcctNo (m_oFromGoldEnquiryBean.getAccountNo());// get gold account create date
									ESBAccCreateDateBean m_oAccCreateDateBean = mService.getAccCreateDate (m_oRequest);
//									responseBean905.setFromAccountCreateDate(m_oAccCreateDateBean.getDtAccOpen ());
									m_sFrmAccCrtDt = m_oAccCreateDateBean.getDtAccOpen ();
									
									// To Account creation Date
									m_oRequest.setAcctNo (m_sToRegAccount); //get saving account create date
									m_oAccCreateDateBean = mService.getAccCreateDate (m_oRequest);
//									responseBean904.setToAccountCreateDate(m_oAccCreateDateBean.getDtAccOpen ());
									m_sToAccCrtDt = m_oAccCreateDateBean.getDtAccOpen ();
			                    	
							}
							else
							{
								m_boIsResultSuccessful = false;

								m_sTransStatus = ResourcesUtils.getUnsuccessful ();
								m_sTransStatusMsg = msgResponse.getErrorMessage ();
							}
						}
						catch (IBBusinessException esbBusinessException)
						{
							/*
							 * catches Business Exception from ESB.intrabankFundTransfer()
							 */
							m_boIsResultSuccessful = false;

							m_sTransStatus = ResourcesUtils.getUnsuccessful ();
							m_sTransStatusMsg = esbBusinessException.getErrorMessage ();
						}
//						m_sFrmAccCrtDt = m_oReturnedESBBean.getFromAccountCreateDate();
//						m_sToAccCrtDt = m_oReturnedESBBean.getToAccountCreateDate();
					}
		        }
            }
			else	// create SI transaction
            {
				/*
				 * check SI limit against amount per transaction
				 */
				m_sServiceCode = m_sSIServiceCode;
//				m_oSIServiceInfoBean = IBUtils.getServiceInfoBean (m_sServiceCode, getIBDynaBean (), getIBSessionObjects (), false);
//	            m_sSIServiceMaxLimit = (String) m_oSIServiceInfoBean.get (ServiceInfo.BEAN_ATT_MAX_LIMIT);

				Map m_oSIBankLimitReturnMap = IBGold3rdPartyTransferBaseServices.checkIntraTransferDailyLimit (this,
	            		getIBDynaBean (), getIBSessionObjects (), m_sLocalAmountStr, m_sEffectiveDate, m_boSIIndicator, m_boIsScheduler);

//				m_fUserLimit = IBGoldTransferDBUtils.getUserTransferLimit (getIBSessionObjects (), m_sServiceCode, m_boIsScheduler);
//
//	            Map m_oSIUserLimitReturnMap = IBGold3rdPartyTransferBaseServices.checkIntraTransferDailyLimitByServiceCode (this,
//						m_sLocalAmountStr, m_sSIServiceMaxLimit, m_fUserLimit, m_sServiceCode, m_sEffectiveDate, m_boSIIndicator, m_boIsScheduler);

				if (!((Boolean) m_oSIBankLimitReturnMap.get (ThirdPartyGoldTransferTags.STATUS)).booleanValue ())
	            {
	            	m_boIsResultSuccessful = false;

	                m_sTransStatus = ResourcesUtils.getUnsuccessful ();
	                m_sTransStatusMsg = ResourcesUtils.getBusinessExceptionErrorMessage (IBBusinessException.SI, SIConstants.ERR_BANK_MAX_LIMIT,
							new String [] { FormatterUtils.formatGoldUnitDisplay ((String) m_oSIBankLimitReturnMap.get (ThirdPartyGoldTransferTags.MAX_LIMIT), true) });
	            }
//	            else if (!((Boolean) m_oSIUserLimitReturnMap.get (ThirdPartyGoldTransferTags.STATUS)).booleanValue ())
//				{
//	            	m_boIsResultSuccessful = false;
//
//					m_sTransStatus = ResourcesUtils.getUnsuccessful ();
//					m_sTransStatusMsg = ResourcesUtils.getBusinessExceptionErrorMessage (IBBusinessException.SI, SIConstants.ERR_USER_MAX_LIMIT,
//							new String [] { FormatterUtils.formatMoneyDisplay ( (String)m_oSIUserLimitReturnMap.get (SIConstants.MAX_LIMIT),
//									null, true) });
//				}
	            else
	            {
//	            	SI created. Will pending on scheduler.
					m_boIsResultSuccessful = true;
					m_sTransStatus = ResourcesUtils.getAccepted ();
	            }
            }

			if (m_boIsResultSuccessful)
			{
				if (SI_PAYMENT_MODE.PAY_NOW.getCode ().equals (m_sPaymentMode))
				{
                    if (!DataValidator.isEmptyString (m_sEmail))
					{
                    	/*
                    	 * email transfer notification to recipient
                    	 */
                    	String m_sSubject = ResourcesUtils.getApplicationResourceMessage ("ib104.thirdparty.email.subject");
                    	
                    	StringBuffer m_sbEmailMsg = new StringBuffer ();
                    	m_sbEmailMsg.append (ResourcesUtils.getApplicationResourceMessage ("ib104.thirdparty.email.greetCustomer", new String [] {m_sSubject, m_sAccountHolderName} ));
                    	m_sbEmailMsg.append (ResourcesUtils.getApplicationResourceMessage ("ib104.thirdparty.email.note1",
                    			new String [] {m_sCustomerName,
                    				DateTimeUtils.formatDayMonthYear (m_oCurrentBVIDateTime).concat (" ").concat (m_oCurrentBVIDateTime.getTime()) } ));

                    	IBLogWriter m_oTableCreater = new IBLogWriter();
                    	m_sbEmailMsg.append (m_oTableCreater.RowCreater ("S", ResourcesUtils.getApplicationResourceMessage ("general.status"), m_sTransStatus, null, null)).append("\n");
                    	m_sbEmailMsg.append (m_oTableCreater.RowCreater ("C", ResourcesUtils.getApplicationResourceMessage ("general.amount"), m_sAmountDis, null, null)).append("\n");
                    	m_sbEmailMsg.append (m_oTableCreater.RowCreater ("C", ResourcesUtils.getApplicationResourceMessage ("general.reference.number"), m_sFormattedTransId, null, null)).append("\n");
                    	if(!DataValidator.isEmptyString (m_sHostRefNo))
        				{
                    		m_sbEmailMsg.append (m_oTableCreater.RowCreater ("C", ResourcesUtils.getApplicationResourceMessage ("general.reference"), m_sHostRefNo, null, null)).append("\n");
        				}
                    	m_sbEmailMsg.append (m_oTableCreater.RowCreater ("E", ResourcesUtils.getApplicationResourceMessage ("ib104.transferReference"),
                    			DataValidator.isEmptyString (m_sUserTransferRef) ? "-" : m_sUserTransferRef, null, null)).append("\n");

                    	m_sbEmailMsg.append (ResourcesUtils.getApplicationResourceMessage ("ib104.thirdparty.email.note2"));
                    	m_sbEmailMsg.append (ResourcesUtils.getApplicationResourceMessage ("ib104.thirdparty.email.disclaimer"));

                    	IBUtils.sendEmail (this, null, m_sEmail, m_sSubject, m_sbEmailMsg.toString (), m_sTransStatus, null);
                    }
				}

				/*
                 * receipt
                 */
                m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("receipt.transaction.type"), m_sServiceName);
                m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("general.beneficiary.name"), m_sAccountHolderName);
                m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("general.status"), m_sTransStatus);
                m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("general.toAccount"), m_sToRegAccount);
                m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("general.amount"), m_sAmountDis);

                if (!DataValidator.isEmptyString (m_sUserTransferRef))
                {
                	m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("ib104.transferReference"), m_sUserTransferRef);
                }
                if (!DataValidator.isEmptyString (m_sEmail))
                {
                	m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("ib104.beneficiary.email"), m_sEmail);
                }
                if (!DataValidator.isEmptyString (m_sPaymentModeDisplay))
				{
                	m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("ib112.si.payment.mode"), m_sPaymentModeDisplay);
				}
				if (!DataValidator.isEmptyString (m_sPaymentFrequencyDisplay))
				{
					m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("general.payment.frequency"), m_sPaymentFrequencyDisplay);
				}
				if (!DataValidator.isEmptyString (m_sEffectiveDateDisplay))
				{
					m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("general.start.date"), m_sEffectiveDateDisplay);
				}
				if (!DataValidator.isEmptyString (m_sTerminationDateDisplay))
				{
					m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("general.terminate.date"), m_sTerminationDateDisplay);
				}
                m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("general.reference.number"), m_sFormattedTransId);
                if(!DataValidator.isEmptyString (m_sHostRefNo))
				{
                	m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("general.reference"), m_sHostRefNo);
				}
                m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("general.transaction.date"),
                		DateTimeUtils.formatDayMonthYear (m_oCurrentBVIDateTime));
                m_oReceiptMap.put (ResourcesUtils.getApplicationResourceMessage ("general.transaction.time"),
                		m_oCurrentBVIDateTime.getTime ());

                /*
                 * log into IB_RECEIPT_DETAIL
                 */
                IBUtils.loopIntoReceiptDetails (this, m_oReceiptMap, m_oCurrentBVIDateTime.getSimpleDate (), m_sTransId);

                m_oViewBean.set (CommonConstants.RECEIPT_MAP, m_oReceiptMap);

                String m_sReceiptLink = IBUtils.getReceiptLink (ThirdPartyGoldTransferTags.REG_THIRDPARTY_GOLD_TRANSFER_FORM, FAV_VIEWBEAN);
                m_oViewBean.set (CommonConstants.RECEIPT_LINK, m_sReceiptLink);
			}

			StringBuffer m_sbDescription = new StringBuffer (ThirdPartyGoldTransferTags.DESC_TRANSFER_INTRA_REGISTERED)
            	.append (" (")
            	.append (FormatterUtils.formatCustomerName(m_sAccountHolderName))
            	.append (")");

			if (!DataValidator.isEmptyString (m_sHostRefNo))
			{
				m_sbDescription.append ("<br>")
	            	.append ("(")
	            	.append (ResourcesUtils.getApplicationResourceMessage ("general.reference.number.short")).append (": ").append (m_sHostRefNo)
	            	.append (")");
			}

			/*
			 * log into IB_INTRA_GOLD_TRANSFER
			 */
			IBLoggerExtension.logTransferGold (this,
					m_sTransId,
					m_sServiceName,
					m_oCurrentBVIDateTime,
					m_sFromAccount,
					m_sFromIsoCurrency,
					m_sToRegAccount,
					m_sToIsoCurrency,
					m_sLocalAmountStr,
					m_sAmount,
					m_sUserTransferRef,
					m_sTransStatus,
					m_sTransStatusMsg,
					DateTimeUtils.convertStringToBVIDateTime (m_sEffectiveDate, "yyyyMMdd"),
					getIBSessionObjects ().getRemoteIPAddress (),
					m_sbDescription.toString (),
					m_sHostRefNo,
					m_sServiceCode,
					"","",
					m_sFrmAccCrtDt,
					m_sToAccCrtDt,
					m_sAccountHolderName,
					m_sEmail,
					String.valueOf (DataUtils.convertBooleanToInt (m_boSIIndicator)),
					m_sRimNo,m_sCustomerName);

			//Log into IB_GOLD_HISTORY
			IBLoggerExtension.logGoldHistoryFromTransfer(this, 
					m_sTransId, 
					m_oCurrentBVIDateTime, 
					GoldConstants.TRNX_TYPE_TRANSFER, 
					m_sRimNo, 
					m_sCustomerName, 
					m_sFromAccount, 
					m_sToRegAccount, 
					"", //gold price
					"0" ,//total gold price 
					m_sAmount, 
					m_sFromAccBranchCode, 
					m_sFromAccBranchName, 
					m_sTransStatus, 
					getIBSessionObjects ().getRemoteIPAddress (), 
					m_sServiceCode,
					isStaff,
					DateTimeUtils.convertStringToBVIDateTime (m_sEffectiveDate, "yyyyMMdd"),
					m_sEmail,//email
					String.valueOf (DataUtils.convertBooleanToInt (m_boSIIndicator)));
			
			
			/*
			 * log into IB_TRANSACTION_HISTORY
             * receipt indicator is based whether have receipt or not, based on result status.
             */

			IBLogger.logInetTranHistory (this,
					m_sTransId,
					m_sServiceName,
					m_sFromAccount,
					m_sFromIsoCurrency,
					m_sToRegAccount,
					m_sToIsoCurrency,
					m_sAmount,
					m_sbDescription.toString (),
					m_sTransStatus,
					"","",
					m_sEffectiveDate,
					getIBSessionObjects ().getRemoteIPAddress (),
					"",
					m_boIsResultSuccessful,
					m_sPhx_Ref_no,//to PHX_REFFERENCE_NO, m_sHostRefNo is Auth_code,if fail is null (should change to refference no
					"",
					"","",
					getIBSessionObjects ().getIBSessionId (),
					"","","",
					m_sFrmAccCrtDt,
					m_sToAccCrtDt,
					m_sTransStatusMsg,
					m_sPaymentMode,
					m_sPayFrequency,
					m_sTerminationDate,"",""
                    );

			
			
			if (m_boSIIndicator && m_boIsResultSuccessful)
			{
				IBLogger.logSIDetail (
						this,
						m_sTransId,
						m_sTransId,
						SIConstantsExtension.TRANSCODE_INTRA_GOLD_TRANSFER,
						m_sServiceName,
						m_sPaymentMode,
						m_sPayFrequency,
						m_sEffectiveDate,
						m_sTerminationDate,
						m_sServiceCode,
						m_boDeleteSIIndicator
						);
			}

			if (ResourcesUtils.getAccepted ().equalsIgnoreCase (m_sTransStatus))
			{
				m_sTransStatus = ResourcesUtils.getApplicationResourceMessage ("ib104.statusMessage");
			}

			m_oViewBean.set (ThirdPartyGoldTransferTags.REFERENCE_NO, m_sFormattedTransId);
			m_oViewBean.set (ThirdPartyGoldTransferTags.HOST_REFERENCE_NO, m_sHostRefNo);
			m_oViewBean.set (ThirdPartyGoldTransferTags.IS_RESULT_SUCCESSFUL, Boolean.valueOf (m_boIsResultSuccessful));
			m_oViewBean.set (ThirdPartyGoldTransferTags.STATUS, m_sTransStatus);
			m_oViewBean.set (ThirdPartyGoldTransferTags.REASON, m_sTransStatusMsg);

			/*
			 * TO_DISPLAY_NEW_BALANCE: based on schedule date, if today then display balance, else do not display.
			 */

			m_oViewBean.set (ThirdPartyGoldTransferTags.TO_DISPLAY_NEW_BALANCE, Boolean.valueOf (m_boToDisplayNewBal));
			m_oViewBean.set (ThirdPartyGoldTransferTags.FROM_ACCT_NEW_BAL, FormatterUtils.formatGoldUnitDisplay (m_sNewBalance, true));
			m_oViewBean.set (ThirdPartyGoldTransferTags.TRANS_DATE, DateTimeUtils.formatDayMonthYear (m_oCurrentBVIDateTime));
			m_oViewBean.set (ThirdPartyGoldTransferTags.TRANS_TIME, m_oCurrentBVIDateTime.getTime());

//			 SMS Notification START
			String m_sCustomerSMSMessage = "-";
			String m_sBeneficiarySMSMessage = "-";

			String m_sCustomerAmount = FormatterUtils.formatGoldUnitDisplay (m_sAmount, true);//SMSServices.formatAmountValue(m_sAmount, m_sFromIsoCurrency);
			String m_sBeneficiaryAmount = FormatterUtils.formatGoldUnitDisplay (m_sAmount, true);//SMSServices.formatAmountValue(m_sAmount, m_sToIsoCurrency);
			
			String m_sTransactionTypeForSMSMessage = ResourcesUtils.getApplicationResourceMessage(ThirdPartyGoldTransferTags.RESOURCE_SMS_TEXT_MESSAGE_SERVICE_THIRD_GOLD);
			
			m_sCustomerSMSMessage = SMSServices.generateCustomerOtherSMSMessage(
					m_sTransactionTypeForSMSMessage, 
					m_sCustomerAmount, 
					m_sTransStatus, 
					m_oCurrentBVIDateTime,
					m_sAccountHolderName.length()>8?m_sAccountHolderName.substring(0, 8):m_sAccountHolderName);
			
					
//			SMSServices.sendCustomerSMS(this, 
			SMSServiceGold.sendCustomerSMS2(this,
					m_oViewBean, 
					m_sFromAccount, 
					m_sTransStatus, 
					getIBDynaBean().get(SIConstants.PAY_MODE).toString(), 
					m_sServiceName, 
					m_sTransId,
					m_sAmount, 
					getIBSessionObjects().getVisitor().getId(), 
					m_sCustomerSMSMessage, 
					m_oCurrentBVIDateTime);
			
			m_sBeneficiarySMSMessage = SMSServices.generateBeneficiaryOtherSMSMessage(
					m_oViewBean, 
					m_sTransactionTypeForSMSMessage,
					m_sToRegAccount, 
					m_sBeneficiaryAmount, 
					m_oCurrentBVIDateTime);
			
//			SMSServices.sendBeneficiarySMS(this, 
			SMSServiceGold.sendBeneficiarySMS2(this, 
					getIBDynaBean(),
					m_oViewBean, 
					m_sFromAccount, 
					m_sTransStatus, 
					getIBDynaBean().get(SIConstants.PAY_MODE).toString(), 
					m_sServiceName, 
					m_sTransId,
					getIBSessionObjects().getVisitor().getId(), 
					m_sBeneficiarySMSMessage, 
					m_oCurrentBVIDateTime);
			
//			ESBAccountEnquiryTC100Bean m_oTCEnquiryBean = getESBServices ().getAccountDetailsTC100 (m_sFromAccount);
			

			// UAT START
			m_oViewBean.set(SMSConstants.VBEAN_SMS_UAT_IS_BENE_SMS_SENT, SMSServices.isSMSLogged(this, m_oViewBean.get(SMSConstants.VBEAN_SMS_BENE_MOBILE_NO).toString(), SMSConstants.SMS_NOTIFICATION_TYPE, m_oCurrentBVIDateTime.getDateDDMMMYYYYHMS()));
			m_oViewBean.set(SMSConstants.VBEAN_SMS_UAT_IS_CUSTOMER_SMS_SENT, SMSServices.isSMSLogged(this, m_oViewBean.get(SMSConstants.VBEAN_SMS_CUSTOMER_MOBILE_NO).toString(), SMSConstants.SMS_NOTIFICATION_TYPE, m_oCurrentBVIDateTime.getDateDDMMMYYYYHMS()));
			m_oViewBean.set(SMSConstants.VBEAN_SMS_UAT_BENE_SMS_MESSAGE, m_sBeneficiarySMSMessage);
			m_oViewBean.set(SMSConstants.VBEAN_SMS_UAT_CUSTOMER_SMS_MESSAGE, m_sCustomerSMSMessage);
			// UAT END

			// SMS Notification END
			
			getIBDynaBean ().set (FAV_VIEWBEAN, m_oViewBean);

			/*
             * clear session after transfer,
             * so account enquiry will not display balance in session,
             * instead get from host in new session
             */
			getIBSessionObjects ().setAccountEnquiryBean (null);
		}
		catch (Exception e)
		{
			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);
	}
}
