
/********************************************************
	Title : BondEJB
	Date  : 17/10/08
	Author: pankaj singh

********************************************************/

package ibase.webitm.ejb.eou;

import ibase.system.config.ConnDriver;
import ibase.webitm.ejb.ValidatorEJB;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;

import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.GregorianCalendar;
import javax.ejb.CreateException;
import javax.ejb.SessionBean;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.sql.Timestamp;

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

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

//public class BondEJB extends ValidatorEJB implements SessionBean
@Stateless //added for ejb3
public class Bond extends ValidatorEJB implements BondLocal, BondRemote 
{
	/*public void ejbCreate() throws RemoteException, CreateException
	{
		System.out.println("<======= StrgSeries DISPLAY IS IN PROCESS ! \n Welcome!========>");
	}
	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
	{
		String errString = null;
		Document dom = null;
		Document dom1 = null;
		Document dom2 = null;
		try
		{
			dom = parseString(xmlString);
			dom1 = parseString(xmlString1);
			if (xmlString2.trim().length() > 0 )
			{
				dom2 = parseString("<Root>" + xmlString2+ "</Root>");
			}
			errString = wfValData(dom,dom1,dom2,objContext,editFlag,xtraParams);
		}
		catch(Exception e)
		{
			System.out.println("Exception : ItemEJB : wfValData(String xmlString) : ==>\n"+e.getMessage());
		}
		return (errString);
	}
	public String wfValData(Document dom, Document dom1,Document dom2, String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		int ctr=0;
		String childNodeName = null;
		String errString = "";
		String errCode = "",errcode = "";
		Connection conn = null;
		PreparedStatement pstmt = null ;
		ResultSet rs = null , rs1 = null;
		String sql = "" ,sql1 = "";
		String userId = "";
		String effFromStr = null;
		String validUptoStr = null,bankCode = "";
		String divHead="";
		double minAmount = 0;
		double maxAmount = 0;
		int cnt = 0,cnt1 = 0;
		int currentFormNo=0;
		int childNodeListLength;
        ConnDriver connDriver = new ConnDriver();
		String siteCode = "";
		SimpleDateFormat simpleDateFrormat = null;
		Date effFrom = null,validUpto = null;
		try
		{
			
			conn = connDriver.getConnectDB("DriverITM");
			connDriver = null;
			userId = getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			GenericUtility genericUtility = GenericUtility.getInstance();
			simpleDateFrormat = new SimpleDateFormat("mm/dd/yy");
			if(objContext != null && objContext.trim().length()>0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}
			switch(currentFormNo)
			{
				case 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();

						if (childNodeName.equalsIgnoreCase("site_code"))
						{
							siteCode = getColumnValue("site_code",dom);
							sql = "select count(*)  from site where site_code = ?";
							pstmt = conn.prepareStatement(sql);
							pstmt.setString(1,siteCode);
							rs = pstmt.executeQuery();
							if(rs.next())
							{
								cnt = rs.getInt(1);
							}
							pstmt.close();
							rs.close();
							pstmt = null;
							rs = null;
							if (cnt == 0) 
							{	   
								errCode = "VMSITE1";
								errString = getErrorString("site_code",errCode,userId);
								 break;
							}
						}// End Of site_code
						else if (childNodeName.equalsIgnoreCase("bank_code"))
						{
							bankCode = getColumnValue("bank_code",dom);
							sql = "select count(1)  from bank where bank_code = ? ";
							pstmt = conn.prepareStatement(sql);
							pstmt.setString(1,bankCode);
							rs = pstmt.executeQuery();
							if(rs.next())
							{
								cnt = rs.getInt(1);
							}
							pstmt.close();
							rs.close();
							pstmt = null;
							rs = null;
							if (cnt == 0) 
							{	   
								errCode = "VTBANK1";
								errString = getErrorString("bank_code",errCode,userId);
								 break;
							}
						}// End Of bank_code
						
						else if ( childNodeName.equalsIgnoreCase( "valid_upto" ) )
						{
							validUptoStr = getColumnValue( "valid_upto", dom );
							effFromStr = getColumnValue( "eff_from", dom );
							System.out.println(" 'VALID UPTO' FROM DOM  =========>"+validUpto);
							if( effFromStr == null || effFromStr.trim().length() ==0 || validUptoStr == null || validUptoStr.trim().length() ==0 )
							{
								errCode = "VTVLEFN";
								errString = getErrorString("valid_upto",errCode,userId);
								break;
							}
							else
							{						  
								
								SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getApplDateFormat());
								java.util.Date effFrom1 = sdf.parse(effFromStr);
								java.util.Date validUpto1 = sdf.parse(validUptoStr);
								if(validUpto1.before(effFrom1))
								{	
						            System.out.println(" ====> 'VALID UPTO' DATE  MUST BE GREATER THAN 'EFF FROM' DATE <===== ");
									errCode = "VTDATE6";
									errString = getErrorString("valid_upto",errCode,userId);
						          	break;
								}	
							} // End of (startDate!=null)
						} // end eff_from
						 else if (childNodeName.equalsIgnoreCase("bond_value"))
						{
							Timestamp ValidUpto = null, EffFrom = null;
							String bondValue = "";
							System.out.println("\n U r in bond_value block");
							effFromStr = getColumnValue("eff_from",dom);
							validUptoStr = getColumnValue("valid_upto",dom);
							siteCode = getColumnValue("site_code",dom);
							bondValue = getColumnValue("bond_value",dom);
							System.out.println("\n valid upto str....."+validUptoStr + " eff from :-" + effFromStr);
							effFromStr = effFromStr == null ? "" : effFromStr;
							validUptoStr = validUptoStr == null ? "" : validUptoStr;
				            System.out.println(genericUtility.getDBDateFormat());
							if(effFromStr != null && effFromStr.trim().length() > 0)
							{
								EffFrom = Timestamp.valueOf(genericUtility.getValidDateString(effFromStr,genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat()) + " 00:00:00.0");
							}
				            if(validUptoStr != null && validUptoStr.trim().length() > 0)
							{
								ValidUpto = Timestamp.valueOf(genericUtility.getValidDateString(validUptoStr,genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat()) + " 00:00:00.0");
							}
							if(bondValue == null || bondValue.trim().length() == 0)
							{
								errCode = "VMBNVFNL";
								errString = getErrorString("bond_value",errCode,userId);
								 break;
							}
							else
							{
								/* sql = " select count(*) "
										+ " from b17_bond "
										+ " where  site_code = '" + siteCode + "'"
										+ " and eff_from >= ? "
										+ " and valid_upto <= ? "; */
								
								sql = "select min(eff_from) from b17_bond"
											+ " where  site_code = ? "
											+ " and valid_upto <= ?";
								//System.out.println("sql for bond_value:- " + sql);
								pstmt = conn.prepareStatement(sql);
								pstmt.setString(1,siteCode);
								pstmt.setTimestamp(2,ValidUpto);
								rs = pstmt.executeQuery();
								if(rs.next())
								{
									System.out.println("min eff date" + rs.getTimestamp(1) );
								}
								pstmt.close();
								rs.close();
								pstmt = null;
								rs = null;
								sql = "select max(valid_upto)  from b17_bond"
											+ " where  site_code = ? "
											+ " and eff_from >= ?";
								//System.out.println("sql for bond_value:- " + sql);
								pstmt = conn.prepareStatement(sql);
								pstmt.setString(1,siteCode);
								pstmt.setTimestamp(2,EffFrom);
								rs = pstmt.executeQuery();
								if(rs.next())
								{
									System.out.println("max(valid_upto) " + rs.getTimestamp(1) );
								}
								pstmt.close();
								rs.close();
								pstmt = null;
								rs = null;
								
								sql = "select count(*) from b17_bond  "
											+ " where  site_code = ? " 
											+ " and eff_from >= (select min(eff_from) from b17_bond " 
											+ " where  site_code = ? " 
											+ " and valid_upto <= ? )"
											+ " and valid_upto <= (select max(valid_upto) from b17_bond  "
											+ " where  site_code =  ? " 
											+ " and eff_from >= ? )";
								//System.out.println("sql for bond_value:- " + sql);
								pstmt = conn.prepareStatement(sql);
								pstmt.setString(1,siteCode);
								pstmt.setString(2,siteCode);
								pstmt.setTimestamp(3,ValidUpto);
								pstmt.setString(4,siteCode);
								pstmt.setTimestamp(5,EffFrom);
								rs = pstmt.executeQuery();
								if(rs.next())
								{
									cnt = rs.getInt(1);
								}
								pstmt.close();
								rs.close();
								pstmt = null;
								rs = null;
								System.out.println("Count from db for bond :- " + cnt);
								if( editFlag.equalsIgnoreCase("E") )
								{
									if (cnt > 1) 
									{	   
										errCode = "VTDUBND";
										errString = getErrorString("bond_value",errCode,userId);
										 break;
									}
								}
								else if( editFlag.equalsIgnoreCase("A") )
								{
									if (cnt > 0) 
									{	   
										errCode = "VTDUBND";
										errString = getErrorString("bond_value",errCode,userId);
										 break;
									}
								}
							}
						 } // end bond value
					}//end for	
			} //END switch
		}//END TRY
		catch(Exception e)
		{
			System.out.println("Exception ::"+e);
			e.printStackTrace();
			errString=e.getMessage();
		}
		finally
		{
			try
			{
				if(conn!=null)
				{
					if(pstmt != null )pstmt.close();
					if(rs != null )rs.close();
					if(rs1 != null )rs.close();
					rs = null;
					rs1 = null;
					pstmt =null;
					conn.close();
				}
				conn = null;
			}catch(Exception d)
				{
				  d.printStackTrace();
				}
			System.out.println("[BondEJB] Connection is Closed");
		}
		System.out.println("ErrString ::"+errString);
		return errString;
	}//END OF VALIDATION

	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 = "";
		try
		{
			dom = parseString(xmlString);
			System.out.println("xmlString" + xmlString);
			dom1 = parseString(xmlString1);
			if (xmlString2.trim().length() > 0 )
			{
				dom2 = parseString(xmlString2);
			}
			valueXmlString = itemChanged(dom,dom1,dom2,objContext,currentColumn,editFlag,xtraParams);
		}
		catch(Exception e)
		{
			System.out.println("Exception : [BondEJB][itemChanged(String,String)] :==>\n"+e.getMessage());
		}
        return valueXmlString;
	}
	public String itemChanged(Document dom, Document dom1,Document dom2, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		StringBuffer valueXmlString = new StringBuffer();
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null ;
		int ctr=0;
		String childNodeName = null;
		String columnValue = null;
		String Col_name = "",bankCode = "";
		int currentFormNo = 0 ,cnt = 0;
		int  ShortId = 0;
		String salesPers = "" ,itemSer = "",descr = "", empCodeAprv = "",currAppdate = "",frDate = "",toDate = "";
		String fName = "",lName = "",mName = "";
		
		String sql = "",sql1 = "";
		String loginSite = "", siteCode = "";
		GregorianCalendar cal = new GregorianCalendar();
		ConnDriver connDriver = new ConnDriver();
		GenericUtility genericUtility = GenericUtility.getInstance();
		try
		{
			conn = connDriver.getConnectDB("DriverITM");
			connDriver=null;
			if(objContext != null && objContext.trim().length()>0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}
			System.out.println("FORM NO:::"+currentFormNo);
			System.out.println("\n Extra param........"+xtraParams);
			valueXmlString = new StringBuffer("<?xml version=\"1.0\"?><Root><header><editFlag>");
			valueXmlString.append(editFlag).append("</editFlag></header>");
			valueXmlString.append("<Detail>");

			switch(currentFormNo)
			{
				case 1 :
					parentNodeList = dom.getElementsByTagName("Detail1");
					parentNode = parentNodeList.item(0);
					childNodeList = parentNode.getChildNodes();
					ctr = 0;
					int 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().equalsIgnoreCase("itm_default"))
					{
						loginSite = getValueFromXTRA_PARAMS(xtraParams, "loginSiteCode");
						System.out.println("U r in itm_default");
						valueXmlString.append("<site_code>").append("<![CDATA["+loginSite.trim()+"]]>").append("</site_code>");
						valueXmlString.append("<bond_date>").append("<![CDATA["+getCurrdateAppFormat()+"]]>").append("</bond_date>");
						siteCode = getColumnValue("site_code",dom);
						sql = "select descr,bank_code from site where site_code = '"+loginSite+"'";
						pstmt= conn.prepareStatement(sql);
						rs = pstmt.executeQuery();
						if(rs.next())
						 {
						   descr = rs.getString(1) == null ? "" : rs.getString(1);
						   bankCode = rs.getString(2) == null ? "" : rs.getString(2);
						 }
						pstmt.close();
						rs.close();
						pstmt = null;
						rs = null;
						valueXmlString.append("<site_descr>").append("<![CDATA["+descr.trim()+"]]>").append("</site_descr>");
						if (bankCode != null && bankCode.trim().length() > 0)
						{
							sql = "select bank_name from bank where bank_code = ?";
							pstmt= conn.prepareStatement(sql);
							pstmt.setString(1,bankCode);
							rs = pstmt.executeQuery();
							if(rs.next())
							 {
							   descr = rs.getString(1) == null ? "" : rs.getString(1);
							 }
							pstmt.close();
							rs.close();
							pstmt = null;
							rs = null;
							valueXmlString.append("<bank_code>").append("<![CDATA["+bankCode.trim()+"]]>").append("</bank_code>");
							valueXmlString.append("<bank_bank_name>").append("<![CDATA["+descr.trim()+"]]>").append("</bank_bank_name>");
						
						}
						System.out.println("valueXmlString for itm_default:- " + valueXmlString);
						java.sql.Timestamp currDate = null,currDateTs = null,frDateTs = null,toDateTs = null;
						currDate = new java.sql.Timestamp(System.currentTimeMillis()) ;
						System.out.println("\n today date----" + currDate);
						currAppdate = new SimpleDateFormat(genericUtility.getApplDateFormat()).format(currDate).toString();
						//todayDateDb =  Timestamp.valueOf(currAppdate +" 00:00:00.00");	
						System.out.println("\n today currDate in apl----" + currAppdate);
						currAppdate = genericUtility.getValidDateString(currAppdate,genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat());
						System.out.println("\n today currDate in DB----" + currAppdate);
						currDateTs = Timestamp.valueOf(currAppdate + " 00:00:00.00");
						System.out.println("\n today currDate timeatamp----" + currDateTs);
						sql = "select fr_date,to_date from acctprd "
								+ " where ? between fr_date and to_date";
						System.out.println("select qry from fin date.." + sql);
						pstmt= conn.prepareStatement(sql);
						pstmt.setTimestamp(1,currDateTs);
						rs = pstmt.executeQuery(); 
						if(rs.next())
						{
						   frDateTs = rs.getTimestamp(1);
						   toDateTs = rs.getTimestamp(2);
						}
						System.out.println("frDateTs:- " + frDateTs + "toDate " + toDateTs);
						frDate = genericUtility.getValidDateString(frDateTs.toString(),genericUtility.getDBDateFormat(),genericUtility.getApplDateFormat());
						toDate = genericUtility.getValidDateString(toDateTs.toString(),genericUtility.getDBDateFormat(),genericUtility.getApplDateFormat());
						System.out.println("frDate:- " + frDate + "toDate " + toDate);
						pstmt.close();
						rs.close();
						pstmt = null;
						rs = null;
						valueXmlString.append("<eff_from>").append("<![CDATA["+frDate+"]]>").append("</eff_from>");					
						valueXmlString.append("<valid_upto>").append("<![CDATA["+toDate+"]]>").append("</valid_upto>");					
						
					}
					else if(currentColumn.trim().equalsIgnoreCase("site_code"))
					{
						siteCode = getColumnValue("site_code",dom);
						sql = "select descr from site where site_code = '"+siteCode+"'";
						pstmt= conn.prepareStatement(sql);
						rs = pstmt.executeQuery();
						if(rs.next())
						 {
						   descr = rs.getString(1) == null ? "" : rs.getString(1);
						 }
						pstmt.close();
						rs.close();
						pstmt = null;
						rs = null;
						if(descr == null || descr.trim().length() == 0 )
						{
							valueXmlString.append("<site_descr>").append("").append("</site_descr>");	
						}
						else 
						{
							valueXmlString.append("<site_descr>").append(descr).append("</site_descr>");	
						}
					}
					else if(currentColumn.trim().equalsIgnoreCase("bank_code"))
					{
						bankCode = getColumnValue("bank_code",dom);
						sql = "select bank_name from bank where bank_code = ? ";
						pstmt= conn.prepareStatement(sql);
						pstmt.setString(1,bankCode);
						rs = pstmt.executeQuery();
						if(rs.next())
						 {
						   descr = rs.getString(1) == null ? "" : rs.getString(1);
						 }
						pstmt.close();
						rs.close();
						pstmt = null;
						rs = null;
						if(descr == null || descr.trim().length() == 0 )
						{
							valueXmlString.append("<bank_bank_name>").append("").append("</bank_bank_name>");	
						}
						else 
						{
							valueXmlString.append("<bank_bank_name>").append(descr).append("</bank_bank_name>");	
						}
					}
					else if(currentColumn.trim().equalsIgnoreCase("bank_guarantee"))
					{
						String bankGuarantee = null;
						bankGuarantee = getColumnValue("bank_guarantee",dom);
						valueXmlString.append("<bond_value>").append("<![CDATA["+bankGuarantee.trim()+"]]>").append("</bond_value>");
					}
					else if(currentColumn.trim().equalsIgnoreCase("emp_code__aprv"))
					{
						empCodeAprv = getColumnValue("emp_code__aprv",dom);
						sql = "select emp_fname,emp_mname,emp_lname from employee where emp_code = '" + empCodeAprv + "'";
						pstmt= conn.prepareStatement(sql);
						rs = pstmt.executeQuery();
						if(rs.next())
						 {
						   fName = rs.getString("emp_fname") == null ? "" : rs.getString("emp_fname");
						   mName = rs.getString("emp_mname") == null ? "" : rs.getString("emp_mname");
						   lName = rs.getString("emp_lname") == null ? "" : rs.getString("emp_lname");
						 }
						pstmt.close();
						rs.close();
						pstmt = null;
						rs = null;
						valueXmlString.append("<employee_emp_fname>").append("<![CDATA["+fName.trim()+"]]>").append("</employee_emp_fname>");
						valueXmlString.append("<employee_emp_mname>").append("<![CDATA["+mName.trim()+"]]>").append("</employee_emp_mname>");
						valueXmlString.append("<employee_emp_lname>").append("<![CDATA["+lName.trim()+"]]>").append("</employee_emp_lname>");
					}
					valueXmlString.append("</Detail>");
				break;
		   	}//end of switch
			valueXmlString.append("</Root>");
		}//END OF TRY
		catch(Exception e)
		{
			e.printStackTrace();
			System.out.println("Exception ::"+e.getMessage());
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if(conn!=null)
				{
					if(pstmt != null)pstmt.close();
					if(rs != null)rs.close();
					rs = null;
					pstmt = null;
					conn.close();
				}
				conn = null;
			}catch(Exception d)
			{
			  d.printStackTrace();
			}
			System.out.println("[BondEJB] CONNECTION is CLOSED");
		}
		System.out.println("valueXmlString:::::"+valueXmlString.toString());
		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;
    }
 }// END OF MAIN CLASS