/**
 * VALLABH KADAM 
 * EmployeeSecuritySubmit.java
 * Req Id:-[A16HSUN008]
 * */

package ibase.webitm.ejb.adm.adv;

import java.rmi.RemoteException;
import java.sql.*;
import java.text.SimpleDateFormat;
//import java.util.ArrayList;
import java.util.Calendar;

import ibase.utility.E12GenericUtility;
import ibase.utility.UserInfoBean;

import ibase.webitm.ejb.*;
import ibase.system.config.*;
import javax.naming.InitialContext;

import ibase.webitm.ejb.ITMDBAccessEJB;

import ibase.webitm.utility.ITMException;

import javax.ejb.Stateless; // added for ejb3

@Stateless
public class EmployeeSecuritySubmit extends ActionHandlerEJB implements EmployeeSecuritySubmitLocal,EmployeeSecuritySubmitRemote
{	
	int updateSubStat=0;
	E12GenericUtility genericUtility= new  E12GenericUtility();
	
	@Override	
	public String actionHandler() throws RemoteException,ITMException
	{
		return "";
	}
	public String actionHandler(String tranID, String xtraParams, String forcedFlag) throws RemoteException,ITMException
	{
		System.out.println("EmployeeSecuritySubmit.actionHandler()");
		System.out.println("\t tranId : " + tranID + "\n\t xtraParams" + xtraParams + "\n\t forcedFlag" + forcedFlag);
		String  retString = null;
		UserInfoBean userInfoBean=null;
		retString = actionHandler(tranID, xtraParams, forcedFlag, userInfoBean);
		return retString;
	}
	
	public String actionHandler(String tranID, String xtraParams, String forcedFlag, UserInfoBean userInfoBean) throws RemoteException,ITMException
	{
		System.out.println("EmployeeSecuritySubmit.actionHandler()");
		System.out.println("\t tranId : " + tranID + "\n\t xtraParams" + xtraParams + "\n\t forcedFlag" + forcedFlag);

		String  retString = null;
		try
		{
			retString = actionSubmit(tranID, xtraParams, forcedFlag);
		}
		catch(Exception e)
		{
			System.out.println("Exception :LoanOpeningCncEJB :actionHandler :" + e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		System.out.println("returning String from LoanOpeningCncEJB :actionHandler :"+retString);
		return retString;
	}
    public String actionSubmit(String tranID, String xtraParams, String forcedFlag) throws RemoteException, ITMException
    {
	    // TODO Auto-generated method stub
		
		System.out.println("Inside EmployeeSecuritySubmit cancel() method");
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = "";
		ConnDriver connDriver = null;
		
		InitialContext initialCtx = null;
		ITMDBAccessLocal itmDBAccess = null;
		AppConnectParm appConnect = null;
	
//		ArrayList<String> errList = new ArrayList<String>();
//		ArrayList<String> errFields = new ArrayList<String>();
		
		String status="";
		String loginCode = "", chgTerm = "",chgUser="";

		connDriver = null;
		String errString = "";
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();

		Timestamp sysDate = null;
		E12GenericUtility genericUtility=new E12GenericUtility();
		
		
		try
        {
	        connDriver = new ConnDriver();
	        conn = connDriver.getConnectDB("DriverITM");
	        connDriver = null;
	        conn.setAutoCommit(false);
	        
	        appConnect = new AppConnectParm();
			initialCtx = new InitialContext(appConnect.getProperty());
	        itmDBAccess = (ITMDBAccessLocal)initialCtx.lookup("ibase/ITMDBAccessEJB/local");
	        
	        
	        Calendar currentDate = Calendar.getInstance();
			SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getApplDateFormat());
			String sysDateStr = sdf.format(currentDate.getTime());
			
			sysDate=Timestamp.valueOf(genericUtility.getValidDateString(sysDateStr, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat())
					+ " 00:00:00.0");
			
			chgTerm = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"termId");
			chgUser = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			System.out.println("CHG_term 111 :- ["+chgTerm+"]");
			System.out.println("CHG_user 111 :- ["+chgUser+"]");
		
	        System.out.println("@V@ Tran Id fornd by transaction :- ["+tranID+"]");		
			
			sql = "select status from emp_securities_hdr where tran_id=?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, tranID);
			rs = pstmt.executeQuery();
			while(rs.next())
			{
				status = rs.getString("status");
			}
			pstmt.close();
			pstmt=null;
			rs.close();
			rs=null;
			
			
			/**
			 * Check transaction is already Canceled
			 * */
			if("N".equalsIgnoreCase(status))
			{
//				errList.add("VTALRDCACL");
//				errFields.add("status");
				errString = itmDBAccess.getErrorString("", "VTALRDCACL", "", "", conn);
				return errString;
			}
			/**
			 * Check transaction is already Submmited
			 * */
			else if("S".equalsIgnoreCase(status))
			{
//				errList.add("VTALRDSUB");
//				errFields.add("status");
				errString = itmDBAccess.getErrorString("", "VTALRDSUB", "", "", conn);
				return errString;
			}
			else
			{
				sql = "update emp_securities_hdr set status = 'S',status_date=?, chg_term=?, chg_user=?,chg_date=? where tran_id=?";
				pstmt=conn.prepareStatement(sql);
				pstmt.setTimestamp(1, sysDate);
				pstmt.setString(2, chgTerm);
				pstmt.setString(3, chgUser);
				pstmt.setTimestamp(4, sysDate);
				pstmt.setString(5, tranID);
				updateSubStat=pstmt.executeUpdate();
				
				if(updateSubStat > 0)
				{
					/**
					 * Submit success
					 * */
					errString = itmDBAccess.getErrorString("", "VTSUBSUCSS", "", "", conn);
				}
				else
				{
					/**
					 * Submit fail
					 * */
					errString = itmDBAccess.getErrorString("", "VTSUBFAIL", "", "", conn);
				}
			}			
        } 
		catch (SQLException e)
        {
	        e.printStackTrace();
        }
		catch (Exception e)
        {
	        e.printStackTrace();
        }
		finally 
		{
			try
			{
				if(!conn.isClosed())
				{
					if(updateSubStat>0)
					{
						conn.commit();		
					}
					else
					{
						conn.rollback();
					}				
				conn.close();
				}				
				if (rs != null)
				{
					rs.close();
					rs = null;
				}
				if (pstmt != null) 
				{
					pstmt.close();
					pstmt = null;
				}				
			}
			catch (Exception e)
			{
				System.out.println("Exception : " + e);
				e.printStackTrace();
				throw new ITMException(e);
			}
		}
		
	    return errString;
    }
	private String errorType(Connection conn, String errorCode) throws ITMException 
	{
		String msgType = "";
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try 
		{
			String sql = " SELECT MSG_TYPE FROM MESSAGES WHERE MSG_NO = ? ";

			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, errorCode);
			rs = pstmt.executeQuery();
			while (rs.next()) 
			{
				msgType = rs.getString("MSG_TYPE");
			}
		} 
		catch (Exception ex) 
		{
			ex.printStackTrace();
			throw new ITMException(ex);
		} 
		finally 
		{
			try 
			{
				if (rs != null) 
				{
					rs.close();
					rs = null;
				}
				if (pstmt != null) 
				{
					pstmt.close();
					pstmt = null;
				}
			} 
			catch (Exception e) 
			{
				e.printStackTrace();
				throw new ITMException(e);
			}
		}
		return msgType;
	}
	
	private String saveData(String siteCode,String xmlString, Connection conn) throws ITMException
	{
		System.out.println("saving data...........");
		InitialContext ctx = null;
		String retString = null;
		MasterStatefulLocal masterStateful = null; // for ejb3
		try
		{
			AppConnectParm appConnect = new AppConnectParm();
			ctx = new InitialContext(appConnect.getProperty());
			masterStateful = (MasterStatefulLocal)ctx.lookup("ibase/MasterStatefulEJB/local");
			System.out.println("-----------masterStateful------- " + masterStateful);
			String [] authencate = new String[2];
			authencate[0] = "";
			authencate[1] = "";
			System.out.println("xmlString to masterstateful [" + xmlString + "]");
			retString = masterStateful.processRequest(authencate, siteCode, true, xmlString,true,conn);
			System.out.println("--retString - -"+retString);
		}
		catch(ITMException itme)
		{
			System.out.println("ITMException :CreateDistOrder :saveData :==>");
			throw itme;
		}
		catch(Exception e)
		{
			e.printStackTrace();
			System.out.println("Exception :CreateDistOrder :saveData :==>");
			throw new ITMException(e);
		}
		return retString;
	}
//	private String generateTranId( String windowName, String siteCode, String tranDateStr, Connection conn) throws ITMException
//	{
//		PreparedStatement pstmt = null;
//		ResultSet rs = null;
//		String selSql = "";
//		String tranId = "";
//		String tranSer = "";
//		String keyString = "";
//		String keyCol = "";
//		String xmlValues = "";
//
//		try
//		{
//			System.out.println("generateTranId() called...");
//
//			selSql = "SELECT KEY_STRING, TRAN_ID_COL, REF_SER FROM TRANSETUP WHERE TRAN_WINDOW = ? ";
//			pstmt = conn.prepareStatement(selSql);
//			pstmt.setString( 1, windowName );
//			rs = pstmt.executeQuery();
//			if (rs.next())
//			{
//				keyString = rs.getString("KEY_STRING");
//				keyCol = rs.getString("TRAN_ID_COL");
//				tranSer = rs.getString("REF_SER");
//			}
//			pstmt.close();
//			pstmt=null;
//			rs.close();
//			rs=null;
//			
//			System.out.println("keyString :"+keyString);
//			System.out.println("keyCol :"+keyCol);
//			System.out.println("tranSer :"+tranSer);
//
//			xmlValues ="<?xml version=\"1.0\" encoding=\"utf-8\"?><Root>";
//			xmlValues = xmlValues + "<Header></Header>";
//			xmlValues = xmlValues + "<Detail1>";
//			xmlValues = xmlValues +		"<tran_id></tran_id>";
//			xmlValues = xmlValues +		"<site_code>" + siteCode + "</site_code>";
//			xmlValues = xmlValues +		"<tran_date>" + tranDateStr + "</tran_date>"; 
//			xmlValues = xmlValues + "</Detail1></Root>";
//			System.out.println("xmlValues  :["+xmlValues+"]");
//			TransIDGenerator transIDGenerator = new TransIDGenerator(xmlValues, "BASE", CommonConstants.DB_NAME);
//			tranId = transIDGenerator.generateTranSeqID(tranSer, keyCol, keyString, conn);
//			System.out.println("tranId :"+tranId);
//		}
//		catch (SQLException ex)
//		{
//			System.out.println("Exception :EmpMaritalStatusConf :generateTranId :SQLException ::" +selSql+ ex.getMessage() + ":");
//			ex.printStackTrace();
//			throw new ITMException(ex);
//		}
//		catch (Exception e)
//		{
//			System.out.println("Exception :EmpMaritalStatusConf :generateTranId :Exception ::" + e.getMessage() + ":");
//			e.printStackTrace();
//			throw new ITMException(e);
//		}
//		finally
//		{
//			try
//			{
//				if (rs != null)
//				{
//					rs.close();
//					rs = null;
//				}
//				if (pstmt != null)
//				{
//					pstmt.close();
//					pstmt = null;
//				}
//			}
//			catch(Exception e)
//			{
//				e.printStackTrace();
//				throw new ITMException(e);
//			}
//		}
//		return tranId;
//	}
	private String checkNull(String input)
	{
		if (input == null || ("null").equalsIgnoreCase(input.trim()))
		{
			input = "";
		}
		else
		{
			input = input.trim();
		}
		return input;
	}
	
	private String replaceNull(String input)
	{
		if (input == null)
		{
			input = "";
		}
		return input;
	}
}
