/**
 * Copyright (c) 2009 Penril Datability (SEA) Sdn Bhd All rights reserved.
 *
 * This software is copyrighted. Under the copyright laws, this software
 * may not be copied, in whole or in part, without prior written consent
 * of Penril Datability (SEA) Sdn Bhd or its assignees. This software is
 * provided under the terms of a license between Penril Datability (SEA)
 * Sdn Bhd and the recipient, and its use is subject to the terms of that
 * license.
 */
package my.com.kfh.enterprise.services.ib106_utility;

import java.text.SimpleDateFormat;
import java.util.Date;

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.ib101_access.AccessConstants;
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.hibernate.tables.onlineMobile.MobileTransaction;
import my.com.kfh.hibernate.tables.onlineMobile.UserActivities; //#-- added by pixa(joo) 20130111
import my.com.kfh.hibernate.utils.onlineMobile.HibernateOnlineMobileReportsUtils; //#-- added by pixa(joo) 20130111
import my.com.kfh.web.utils.DateTimeUtils;
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.ResourcesUtils;
import my.com.kfh.web.utils.constant.TransactionType;
//#-- added by pixa(joo) 20130111

/**
 * <pre>
 * PROGRAMMER: Chang Giat Yeng
 * CHANGE-NO:
 * TASK-NO:
 * DATE CREATED: Oct 10, 2008
 * TAG AS:
 * REASON(S):
 * MODIFICATION:
 * </pre>
 */

/**
 * This class get the result of request TAC.
 */
public class IBTACRequestServices extends IBEnterpriseServicesWorkspace {
	private static Class c_oClass = IBTACRequestServices.class;

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

	/**
	 * <pre>
	 * Format mobile number to be displayed.
	 * Generate TAC number by using UPASS controller.
	 * Log into table SMS_TABLE and SMS TAC number to user if request successfully.
	 * Finally, log into table IB_USER_ACTIVITY and IB_TRANSACTION_HISTORY.
	 * </pre>
	 * 
	 * @throws IBGenericException
	 */
	public void requestTAC() throws IBGenericException
	{
		String m_sMethodName = "requestTAC";
		IBTimer m_oTimer = IBLogger.logBSFNMethodEnteringMessage (c_oClass, m_sMethodName);

		String m_sGeneratedTAC = null;
		IBDynaBean m_oTACViewBean = null;
		String m_sMobileNo = null;
		String m_sTacMsgDisplay = null;
		StringBuffer m_oMobileNoDisplay = new StringBuffer();

		SimpleDateFormat m_oDateTimeFormat = new SimpleDateFormat("dd MMM yyyy HH:mm:ss");
		SimpleDateFormat m_oDateFormat = new SimpleDateFormat("dd MMM yyyy");
		SimpleDateFormat m_oTimeFormat = new SimpleDateFormat("HH:mm:ss");
		Date m_oCurrentDateTime = new Date();
		String m_sTransId = null;
		String m_sStatus = ResourcesUtils.getUnsuccessful ();
		String m_sErrorDetails = null;
		String type = null;
		String service = null;
		String amount = "RM0.00";
		String beneName = "";

		try
		{
			m_oTACViewBean = (IBDynaBean) getIBDynaBean ().get (UtilityConstants.TAC_VIEW);
			if (m_oTACViewBean == null)
			{
				m_oTACViewBean = IBDynaBeanManager.createIBDynaBean (UtilityConstants.TAC_VIEW, getIBDynaBean ().getActionMapping ());
			}

			m_sMobileNo = (String) getIBSessionObjects().getHttpSessionAttrObject(AccessConstants.MOBILE_NO);
			if (m_sMobileNo != null && m_sMobileNo.length() >= 4) {
				m_oMobileNoDisplay.append(m_sMobileNo.substring(0, 4));
				int m_iSubMobileNoSize = m_sMobileNo.substring(4,m_sMobileNo.length()).length();

				for (int i = 0; i < m_iSubMobileNoSize; i++) {
					m_oMobileNoDisplay.append("X");
				}
			}

			m_oTACViewBean.set (UtilityConstants.MOBILE_NO, m_oMobileNoDisplay.toString ());

			m_oTACViewBean.set(UtilityConstants.DATE_TIME_DISPLAY, m_oDateTimeFormat.format (m_oCurrentDateTime));
			m_oTACViewBean.set(UtilityConstants.DATE_DISPLAY, m_oDateFormat.format (m_oCurrentDateTime));
			m_oTACViewBean.set(UtilityConstants.TIME_DISPLAY, m_oTimeFormat.format (m_oCurrentDateTime));

			m_sTransId = IBUtils.getTransactionId (getIBSessionObjects ().getDataManager ());

			// UPASS
			// m_sGeneratedTAC = getIBAuthenticationServices ().userGenerateTac
			// (getIBSessionObjects ().getVisitor ().getUserAlias
			// (),getIBSessionObjects().getIBSessionId());

			// Pixakarft Bank Negara Changes 30th Mar 2013 start
			String[] smsInfo = null;

			IBDynaBean smsViewBean = (IBDynaBean) getIBSessionObjects().getHttpSessionAttrObject(CommonConstants.SMS_VIEW_BEAN);

			if (smsViewBean != null) {
				type = (String) smsViewBean.get(CommonConstants.TYPE_ATTR);
				service = (String) smsViewBean.get(CommonConstants.SERVICE_ATTR);
				beneName =  (String) smsViewBean.get(CommonConstants.BENE_NAME);

				m_sGeneratedTAC = getIBAuthenticationServices().userGenerateTac(getIBSessionObjects().getVisitor().getUserAlias(), getIBSessionObjects().getIBSessionId(),	smsViewBean);

				if (type.equals(CommonConstants.TYPE_TRANS)) {
					amount = (String) smsViewBean.get(CommonConstants.AMOUNT);
					smsInfo = new String[] {ResourcesUtils.getApplicationResourceMessage(UtilityConstants.RESOURCE_KEY_SMS_SERVICE.concat(service)),
							(String) smsViewBean.get(CommonConstants.AMOUNT), beneName, m_sGeneratedTAC,m_oDateFormat.format(m_oCurrentDateTime),m_oTimeFormat.format(m_oCurrentDateTime) };
				} else {
					smsInfo = new String[] {ResourcesUtils.getApplicationResourceMessage(UtilityConstants.RESOURCE_KEY_SMS_SERVICE.concat(service)), m_sGeneratedTAC,
							m_oDateFormat.format(m_oCurrentDateTime),m_oTimeFormat.format(m_oCurrentDateTime) };
				}

				m_sTacMsgDisplay = ResourcesUtils.getApplicationResourceMessage(UtilityConstants.RESOURCE_KEY_SMS_MSG_.concat(type), smsInfo);

			} else {

				m_sGeneratedTAC = getIBAuthenticationServices().userGenerateTac(getIBSessionObjects().getVisitor().getUserAlias(),getIBSessionObjects().getIBSessionId());
				m_sTacMsgDisplay = ResourcesUtils.getApplicationResourceMessage(UtilityConstants.RESOURCE_KEY_SMS_MSG,new String[] {m_sGeneratedTAC,
										m_oDateFormat.format(m_oCurrentDateTime),m_oTimeFormat.format(m_oCurrentDateTime) });
			}
			// Pixakarft Bank Negara Changes 30th Mar 2013 end
			m_oTACViewBean.set(UtilityConstants.GENERATED_TAC, m_sGeneratedTAC);

			getIBDynaBean().set(UtilityConstants.TAC_VIEW, m_oTACViewBean);

			// m_sTacMsgDisplay = ResourcesUtils.getApplicationResourceMessage
			// (UtilityConstants.RESOURCE_KEY_SMS_MSG,
			// new String [] {m_sGeneratedTAC, m_oDateFormat.format
			// (m_oCurrentDateTime), m_oTimeFormat.format
			// (m_oCurrentDateTime)});

			IBLogger.logTACSMS(this, m_sTacMsgDisplay,UtilityConstants.SMS_STATUS_1,"");

			m_sStatus = ResourcesUtils.getSuccessful();
		} catch (Exception e) {
			if (e instanceof IBBusinessException) {
				
				IBBusinessException m_oBizException = (IBBusinessException) e;
				m_sErrorDetails = m_oBizException.getErrorMessage();
			}

			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 {
			IBLogger.logUserActivity(this, 
									 TransactionType.UTILITY_TAC_REQUEST,	
									 TransactionType.UTILITY_TAC_REQUEST+" Type: "+type+" Service: "+service+" Amount:"+amount, 
									 m_sStatus,	
									 getIBSessionObjects().getRemoteIPAddress(), 
									 null);

			StringBuffer details = new StringBuffer();
			
			if(type.equalsIgnoreCase(CommonConstants.TYPE_TRANS)){
				
				details.append("For transaction ");
			}else if(type.equalsIgnoreCase(CommonConstants.TYPE_REQ)){
				
				details.append("For ");
				amount="";
			}
			details.append(ResourcesUtils.getApplicationResourceMessage(UtilityConstants.RESOURCE_KEY_SMS_SERVICE_FULL.concat(service)));
			details.append(" ");
			details.append(amount);
			details.append(" ");
		
			IBLogger.logInetTranHistory(this, 
					                    m_sTransId,
					                    TransactionType.UTILITY_TAC_REQUEST, 
					                    "", 
					                    "", 
					                    "", 
					                    "", 
					                    "",
					                    details.toString(), 
					                    m_sStatus,
					                    DateTimeUtils.formatIBDateTimeToYMD(m_oCurrentDateTime),
					                    getIBSessionObjects().getRemoteIPAddress(), 
					                    "", 
					                    false, 
					                    "",	
					                    getIBSessionObjects().getIBSessionId(),"","");

			// #-- added by pixa(joo) 20130111 start
			try {
				String ChannelObj = "";
				if (getIBSessionObjects().getHttpSessionAttrObject("ChannelObj") != null) {
					ChannelObj = getIBSessionObjects().getHttpSessionAttrObject("ChannelObj").toString();
				}
				if (ChannelObj.equals("mobileApp")) {
					MobileTransaction m_oMobileTransaction = new MobileTransaction();
					m_oMobileTransaction.setDate(new Date());
					m_oMobileTransaction.setRimNo(getIBSessionObjects().getVisitor().getStringValue(AccessConstants.VISITOR_RIM_NO));
					m_oMobileTransaction.setUsername(getIBSessionObjects().getVisitor().getName());
					m_oMobileTransaction.setCustomerName(getIBSessionObjects().getVisitor().getStringValue(AccessConstants.VISITOR_LAST_NAME));
					m_oMobileTransaction.setIbTransactionId(IBUtils.getTransactionId(getIBSessionObjects().getDataManager()));
					m_oMobileTransaction.setTransactionType("1020");
					m_oMobileTransaction.setFromAccount(null);
					m_oMobileTransaction.setFromCy(null);
					m_oMobileTransaction.setToAccount(null);
					m_oMobileTransaction.setToCy(null);
					m_oMobileTransaction.setAmount(null);
					m_oMobileTransaction.setStatus(m_sStatus);
					m_oMobileTransaction.setEffectiveDate(null);
					m_oMobileTransaction.setRemoteIp(getIBSessionObjects().getRemoteIPAddress());
					m_oMobileTransaction.setPhoenixReference(null);
					m_oMobileTransaction.setEpayReference(null);
					m_oMobileTransaction.setPhoenixRevertReferenceNo(null);
					m_oMobileTransaction.setPhoenixChargesReferenceNo(null);
					m_oMobileTransaction.setPhoenixRevertChargesReferen(null);
					m_oMobileTransaction.setDetails(null);
					m_oMobileTransaction.setFromAccountCreationDate(null);
					m_oMobileTransaction.setToAccountCreationDate(null);
					m_oMobileTransaction.setType("IN");

					UserActivities m_oUserActivities = new UserActivities();
					m_oUserActivities.setCardNo("");
					m_oUserActivities.setReference(m_sTransId);
					m_oUserActivities.setActivityDetails(m_sErrorDetails);
					m_oUserActivities.setDeviceName("");
					m_oUserActivities.setDevicePlatform("");
					m_oUserActivities.setDeviceVersion("");
					m_oUserActivities.setIsjailbreak(0);
					HibernateOnlineMobileReportsUtils.insertUserActivityStore(m_oMobileTransaction, m_oUserActivities);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			// #-- added by pixa(joo) 20130111 end
		}

		IBLogger.logBSFNMethodLeavingMessage (c_oClass, m_sMethodName, m_oTimer);
	}
}
