package ibase.webitm.ejb.fin;
import ibase.webitm.ejb.sys.*;

import java.rmi.RemoteException;
import java.text.*;
import java.util.Date;
import java.sql.*;
import org.w3c.dom.*;
import javax.ejb.*;
import ibase.webitm.utility.ITMException;
import ibase.webitm.utility.*;
import ibase.system.config.*;
import ibase.webitm.ejb.*;
import javax.ejb.Stateless; // added for ejb3

@Stateless // added for ejb3
public class BankLimitChkIC extends ValidatorEJB implements BankLimitChkICLocal,BankLimitChkICRemote
{
	GenericUtility genericUtility = GenericUtility.getInstance(); 
	
	UtilMethods utilMethods = UtilMethods.getInstance();

	/*public void ejbCreate() throws RemoteException, CreateException 
	{
	}
	public void ejbRemove()
	{
	}
	public void ejbActivate() 
	{
	}
	public void ejbPassivate() 
	{
	}*/
	public String wfValData() throws RemoteException,ITMException
	{
		return "";
	}

	public String itemChanged() throws RemoteException,ITMException
	{
		return "";
	}
	public String wfValData(String xmlString, String xmlString1,String xmlString2, String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		Document dom = null;
		Document dom1 = null;
		Document dom2 = null;
		String  errString = null;
		System.out.println("Validation Start..........");
		try
		{
			System.out.println("xmlString:::"+xmlString);
			dom = parseString(xmlString);
			dom1 = parseString(xmlString1); 
			if (xmlString2.trim().length() > 0 )
			{
				dom2 = parseString(xmlString2);
			}
			errString = wfValData(dom,dom1,dom2,objContext,editFlag,xtraParams);
		}
		catch(Exception e)
		{
			throw new ITMException( e );
		}
		return (errString);
	}
	public String wfValData(Document dom, Document dom1,Document dom2, String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		String errString = " ";
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		int ctr = 0;
		String startDate = null,endDate = null;
		String columnValue = null;
		String childNodeName = null;
		
		String errCode = null;
		String userId = null,loginSite = null;
		String prdtCode = null;
		
		int cnt = 0;
		int currentFormNo = 0;
		int childNodeListLength;
		Connection conn = null;
		PreparedStatement pstmt=null;
		ResultSet rs = null;
		String sql = null;
		
		String orderDateStr = null;
		String tranDateStr =  null;
		
		int resultCount = 0;
		String templateFile = null;
		String exprNo = null;
		
	    ConnDriver connDriver = new ConnDriver();
    	try
		{
			conn = connDriver.getConnectDB("DriverITM");
			userId = getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			loginSite = getValueFromXTRA_PARAMS(xtraParams, "loginSiteCode");
			genericUtility = GenericUtility.getInstance(); 
			if(objContext != null && objContext.trim().length()>0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}
			switch(currentFormNo)
			{
				case 1 :
					System.out.println("VALIDATION FOR DETAIL [ 1 ]..........");
					parentNodeList = dom.getElementsByTagName("Detail1");
					parentNode = parentNodeList.item(0);
					childNodeList = parentNode.getChildNodes();
					childNodeListLength = childNodeList.getLength();
					for(ctr = 0; ctr < childNodeListLength; ctr++)
					{
						childNode = childNodeList.item(ctr);
						childNodeName = childNode.getNodeName();
					} 
					break;
				case 2 :
					System.out.println("VALIDATION FOR DETAIL [ 2 ]..........");
					parentNodeList = dom.getElementsByTagName("Detail2");
					parentNode = parentNodeList.item(0);
					childNodeList = parentNode.getChildNodes();
					childNodeListLength = childNodeList.getLength();
					for(ctr = 0; ctr < childNodeListLength; ctr++)
					{
						cnt = 0;
						childNode = childNodeList.item(ctr);
						childNodeName = childNode.getNodeName();	
					}
					break;
			}
		}
		catch(Exception e)
		{
			System.out.println("Exception ::" +e);
			e.printStackTrace();
			errCode = "VALEXCEP";
			errString = getErrorString( "", errCode, userId );									
		}
		finally
		{
			try
			{
				if(conn != null)
				{
					if( pstmt != null )
					{
						pstmt.close();
						pstmt = null;
					}
					
					if( rs != null )
					{
						rs.close();
						rs = null;
					}
					conn.close();
				}
				conn = null;
			}
			catch(Exception d)
				{
				  d.printStackTrace();
				}			
			System.out.println(" < ExprProcessIcEJB > CONNECTION IS CLOSED");
		}
		System.out.println("ErrString ::" + errString);

		return errString;
	}

	public String itemChanged(String xmlString, String xmlString1,String xmlString2, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		Document dom = null;
		Document dom1 = null;
		Document dom2 = null;
		String valueXmlString = null;
		try
		{
			dom = parseString(xmlString); 
			System.out.println("xmlString" + xmlString);
			dom1 = parseString(xmlString1); 
			System.out.println("xmlString1" + xmlString1);
			if (xmlString2.trim().length() > 0 )
			{
				System.out.println("xmlString2" + xmlString2);
				dom2 = parseString("<Root>" + xmlString2+ "</Root>");
			}
			valueXmlString = itemChanged(dom,dom1,dom2,objContext,currentColumn,editFlag,xtraParams);
		}
		catch(Exception e)
		{
			throw new ITMException(e);

		}
        return valueXmlString; 
	}
	
	public String itemChanged(Document dom, Document dom1,Document dom2, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		SimpleDateFormat sdf=null;
		Connection conn = null;
		ConnDriver connDriver = new ConnDriver();
		PreparedStatement pStmt = null;
		ResultSet rs = null;
		String sql = null;
		int currentFormNo = 0;
		StringBuffer valueXmlString = new StringBuffer();
		String columnValue = null;

		NodeList parentNodeList = null;
		Node parentNode = null; 
		Node childNode = null;
		NodeList childNodeList = null;
		String childNodeName = null;
		int childNodeListLength = 0;
		int ctr = 0;		
		String  loginSite = null,currDateTs=null;		
		try
		{
			conn = connDriver.getConnectDB("DriverITM");
			connDriver = null;
			if(objContext != null && objContext.trim().length()>0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}
			
			loginSite = getValueFromXTRA_PARAMS(xtraParams, "loginSiteCode");
			
			System.out.println("[BankLimitChkICEJB.java] [itemChanged] :currentFormNo ....." +currentFormNo);
			valueXmlString = new StringBuffer("<?xml version=\"1.0\"?><Root><header><editFlag>");
			valueXmlString.append(editFlag).append("</editFlag></header>");
			GenericUtility genericUtility = GenericUtility.getInstance();
			sdf = new SimpleDateFormat(genericUtility.getDBDateFormat());
			Timestamp currDate = new Timestamp(System.currentTimeMillis());
			currDateTs = sdf.format(currDate).toString();
						
			System.out.println("Current Form No ["+currentFormNo+"]");							
			switch (currentFormNo)
			{
				case 1:
					valueXmlString.append("<Detail1>");	
					parentNodeList = dom.getElementsByTagName("Detail1");
					parentNode = parentNodeList.item(0);
					childNodeList = parentNode.getChildNodes();
					ctr = 0;
					childNodeListLength = childNodeList.getLength();
					do
					{
						childNode = childNodeList.item(ctr);
						childNodeName = childNode.getNodeName();
						if(childNodeName.equals(currentColumn))
						{
							if (childNode.getFirstChild() != null)
							{
								columnValue=childNode.getFirstChild().getNodeValue().trim();
							}
						}
						ctr++;
					}while(ctr < childNodeListLength  && !childNodeName.equals(currentColumn));
					
			 if ( currentColumn.trim().equals( "bank_code" ) )
				{
					String bankName="";
					String siteCode="";
					String siteDescr="";
					String bankCode="";
					String  acctPeriod = "";
					String periodCode="";

					double drAmount =0.0;
					double crAmount=0.0;
					double currentBalance = 0.0;
					double netAmount=0.0;
					double unconfirmPayment =0.0;
					double amount=0.0;
					double balanceAfterConfirm=0.0;
					double crLimit =0.0;

					bankCode = genericUtility.getColumnValue( "bank_code", dom );
					if( bankCode != null )
					{
						sql = "select b.site_code, s.descr site_descr,b.bank_name,"
						+" b.cr_limit from bank b, site s where b.site_code = s.site_code and b.bank_code ='"+bankCode+"' ";
						pStmt = conn.prepareStatement( sql );
						//pStmt.setString(1,bankCode.trim());
						rs = pStmt.executeQuery();	
						
						if( rs.next() )
						{
							siteCode = rs.getString( "site_code" );
							siteDescr = rs.getString( "site_descr" );
							bankName = rs.getString( "bank_name" );
							crLimit = rs.getDouble( "cr_limit" ) ;
						
						}
						rs.close();
						rs = null;
						pStmt.close();
						pStmt = null;
					}
					
					sql="select prd_code from parameter ";				
					pStmt = conn.prepareStatement( sql );
					rs = pStmt.executeQuery();
					if( rs.next() )
					{
						periodCode = rs.getString( "prd_code" ) == null ? "" : rs.getString( "prd_code" ) ;
						
					}
					rs.close();
					rs = null;
					pStmt.close();
					pStmt = null;

					sql="select acct_prd  from period where code='"+periodCode+"' ";				
					pStmt = conn.prepareStatement( sql );
					rs = pStmt.executeQuery();
					if( rs.next() )
					{
						acctPeriod=rs.getString( "acct_prd" ) == null ? "" : rs.getString( "acct_prd" ) ;
						
					}
					rs.close();
					rs = null;
					pStmt.close();
					pStmt = null;	
					
					sql = "select sum(dr_amt__base) as dr_amt__base, sum(cr_amt__base) as cr_amt__base "
					+" from sundrybal where prd_code = 'zzzzzz' and  acct_prd = '"+acctPeriod+"' "
					+" and  site_code = '"+siteCode+"' and sundry_type ='B'	and sundry_code = '"+bankCode+"' " ;
					
					pStmt = conn.prepareStatement( sql );
					rs = pStmt.executeQuery();
					if( rs.next() )
					{
						drAmount = rs.getDouble( "dr_amt__base" );
						crAmount = rs.getDouble( "cr_amt__base" );
						
					}
					rs.close();
					rs = null;
					pStmt.close();
					pStmt = null;
					
					currentBalance= drAmount - crAmount;			

					sql="select sum(net_amt) as net_amount from misc_payment where bank_code = '"+bankCode+"' "
					+" and tran_date <= ? and confirmed = 'N' " ;

					pStmt = conn.prepareStatement( sql );
					pStmt.setTimestamp(1,currDate);
					rs = pStmt.executeQuery();
					if( rs.next() )
					{
						netAmount = rs.getDouble( "net_amount" );
					}
					rs.close();
					rs = null;
					pStmt.close();
					pStmt = null;	
										
					sql="select sum(amount) as amount from fundtransfer where bank_code__from = '"+bankCode+"' "
					+" and tran_date <= ? and link_type <> 'R' and link_type <> 'C' and status = 'E' " ;
					
					pStmt = conn.prepareStatement( sql );
					pStmt.setTimestamp(1,currDate);
					rs = pStmt.executeQuery();
					if( rs.next() )
					{
						amount = rs.getDouble( "amount" );
					
					}
					rs.close();
					rs = null;
					pStmt.close();
					pStmt = null;

					unconfirmPayment = netAmount + amount ;
					balanceAfterConfirm = currentBalance - unconfirmPayment;

					String formatedValue = utilMethods.getReqDecString(balanceAfterConfirm, 2);
					String crLimit_format = utilMethods.getReqDecString(crLimit, 2);
					String currentBalance_format = utilMethods.getReqDecString(currentBalance, 2);
					String unconfirmPayment_format = utilMethods.getReqDecString(unconfirmPayment, 2);

					valueXmlString.append("<bank_name>").append("<![CDATA["+bankName+"]]>").append("</bank_name>");
					valueXmlString.append("<site_code>").append("<![CDATA["+siteCode+"]]>").append("</site_code>");
					valueXmlString.append("<site_descr>").append("<![CDATA["+siteDescr+"]]>").append("</site_descr>");
					valueXmlString.append("<em_limit>").append("<![CDATA["+crLimit_format+"]]>").append("</em_limit>");
					valueXmlString.append("<em_bal>").append("<![CDATA["+currentBalance_format+"]]>").append("</em_bal>");
					valueXmlString.append("<em_unconf>").append("<![CDATA["+unconfirmPayment_format+"]]>").append("</em_unconf>");
					valueXmlString.append("<em_balconf>").append("<![CDATA["+formatedValue+"]]>").append("</em_balconf>");
				}	
					valueXmlString.append("</Detail1>");
					valueXmlString.append("</Root>");	
					break;			
			}
		}
		catch(SQLException sqle)
		{
			System.out.println("Exception sqle ::"+ sqle.getMessage());
		}
		catch(Exception e)
		{
			//System.out.println("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;					
				}
				if ( conn != null )
				{
					conn.close();
					conn = null;
				}
			}
			catch(Exception e)
			{
				System.out.println("Exception ::" + e);
				e.printStackTrace();
			}			
		}
		return valueXmlString.toString();
	}//END OF ITEMCHANGE	
	private String getCurrdateAppFormat()
	{
		String s = "";
		GenericUtility genericUtility = GenericUtility.getInstance();
		try
		{
			java.util.Date date = null;
			Timestamp timestamp = new Timestamp(System.currentTimeMillis());
			System.out.println(genericUtility.getDBDateFormat());

			SimpleDateFormat simpledateformat = new SimpleDateFormat(genericUtility.getDBDateFormat());
			date = simpledateformat.parse(timestamp.toString());
			timestamp = Timestamp.valueOf(simpledateformat.format(date).toString() + " 00:00:00.0");
			s = (new SimpleDateFormat(genericUtility.getApplDateFormat())).format(timestamp).toString();
		}
		catch(Exception exception)
		{
			System.out.println("Exception in  getCurrdateAppFormat " + exception.getMessage());
		}
		return s;
	}
}
