package ibase.webitm.ejb.fin;

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.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;


import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.ejb.Stateless; // added for ejb3
import ibase.webitm.ejb.ITMDBAccessEJB;


@Stateless
public class SiteLoanParty extends ValidatorEJB implements SiteLoanPartyLocal,SiteLoanPartyRemote
{
	GenericUtility genericUtility = GenericUtility.getInstance(); 
	public String wfValData(String xmlString, String xmlString1, String xmlString2,String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		System.out.println("------------ wfvalData method called-----------------");
		String errString = null;
		Document dom = null;
		Document dom1 = null;
		Document dom2 = null;
		try
		{
			dom = parseString(xmlString);
			dom1 = parseString(xmlString1);
			dom2 = parseString(xmlString2);
			errString = wfValData(dom,dom1,dom2,objContext,editFlag,xtraParams);
			
		}
		catch(Exception e)
		{
			System.out.println("Exception : SiteLoanParty.java : wfValData(String xmlString) : ==>\n"+e.getMessage());
			throw new ITMException(e);
		}
		
		return errString;
	} //end of wfValData 
	
	
	
	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 = "";
		Connection conn = null;
		PreparedStatement pstmt = null ;
		ResultSet rs = null;
		String sql = "";
		int cnt=0;
		int currentFormNo=0;
		int childNodeListLength;
		ConnDriver connDriver = new ConnDriver();
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
		
		String siteCode="",salesPerson="",userId="",errCode="",siteCodePay="",crTerm="",taxENV="",taxClass="";
		String PartyCode="",SiteCodePay="",CurrCode = "",CrTerm ="",TaxClass="",TaxEnv="";
		String cnt1 = null;
		String cnt2 = null;
		
		
		
		try
		{
			conn = connDriver.getConnectDB("DriverITM");
			connDriver = null;
			userId = getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			System.out.println("user ID form XtraParam : "+userId);
			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 = genericUtility.getColumnValue("site_code",dom);							


						if (siteCode == null || siteCode.trim().length() == 0 )
						{
								errCode = "VMSITENULL";
								errString = getErrorString("site_code",errCode,userId);
								break;
						}
						else
						{
							sql = "select count(1) 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 = "VMSITENVAL";
								errString = getErrorString("site_code",errCode,userId);
								break;
							}
						}
					}
					if(childNodeName.equalsIgnoreCase("party_code"))
					 {
						 PartyCode=genericUtility.getColumnValue("party_code",dom);
						
						 if(PartyCode==null || PartyCode.trim().length()==0)
						 {
							 errCode = "VMPARTYCD";
							 errString = getErrorString("party_code",errCode,userId);
							break;
						 }
						 else
						 {
							 	sql = "select count(1) from loanparty where  party_code = ? ";
								pstmt=conn.prepareStatement(sql);
								pstmt.setString(1,PartyCode);
								rs = pstmt.executeQuery();
								if(rs.next())
								{
									cnt = rs.getInt(1);
								}
								pstmt.close();
								rs.close();
								pstmt = null;
								rs = null;								
								if(cnt == 0)
								{
									errCode = "VMPARTY1";
									errString = getErrorString("party_code",errCode,userId);
									break;
								}
						 }
						
						 
						 
					 }
					 
					 //----------------------------------------------------
					 if(childNodeName.equalsIgnoreCase("site_code__pay"))
					 {
						 siteCodePay=genericUtility.getColumnValue("site_code__pay",dom);
						 
						 System.out.println("@@-------siteCodePay : "+siteCodePay);	
						 if (siteCodePay !=null && siteCodePay.trim().length() > 0)	
						{	
							 	sql = "select count(1) from site where  site_code = ? ";
								pstmt=conn.prepareStatement(sql);
								pstmt.setString(1,siteCodePay);
								rs = pstmt.executeQuery();
								if(rs.next())
								{
									cnt = rs.getInt(1);
								}
								pstmt.close();
								rs.close();
								pstmt = null;
								rs = null;								
								if(cnt == 0)
								{
									errCode = "VMSITCDPY";
									errString = getErrorString("site_code__pay",errCode,userId);
									break;
								}
								
								///

								siteCode= genericUtility.getColumnValue("site_code",dom);
								 
								if( siteCode != null && siteCode.trim().length() > 0 )
								{	
								 String sql1 = "select fin_entity from site where site_code ='"+ siteCode +"'";
								 Statement st1 = conn.createStatement();
								 ResultSet rs1 = st1.executeQuery(sql1);
								 System.out.println("one1");
								 if(rs1.next())
									{
										cnt1 = rs1.getString(1);
										System.out.println(cnt1);
										System.out.println("three3");
									}
								 rs1.close();
								 rs1 = null;
								 st1.close();
								 st1= null;
								
								}
								 
								if( siteCodePay != null && siteCodePay.trim().length() > 0 )
								{
								String sql2 = "select fin_entity from site where site_code ='"+ siteCodePay +"'";
								 Statement st2 = conn.createStatement();
								 ResultSet rs2 = st2.executeQuery(sql2);
								 System.out.println("two2");
								 
								 if(rs2.next())
									{
										cnt2 = rs2.getString(1);
										System.out.println(cnt2);
										System.out.println("four4");
									}
								 rs2.close();
								 rs2 = null;
								 st2.close();
								 st2= null;
								}
								
							if( !(cnt1.equalsIgnoreCase(cnt2) ))
								 {
									 System.out.println("enter 44");
									 errCode = "VMSITEFN1";
									 errString = getErrorString("site_code__pay",errCode,userId);
									break;
								 }
								 
						}
						 
					 }
					 
					 if(childNodeName.equalsIgnoreCase("curr_code"))
					 {
						 CurrCode=genericUtility.getColumnValue("curr_code",dom);
						 System.out.println("@@-------crTerm : "+CurrCode);
							if (CurrCode !=null && CurrCode.trim().length() > 0)	 
							{							
							 	sql = "select count(1) from FINENT where curr_code = ? ";
								pstmt=conn.prepareStatement(sql);
								pstmt.setString(1,CurrCode);
								rs = pstmt.executeQuery();
								if(rs.next())
								{
									cnt = rs.getInt(1);
								}
								pstmt.close();
								rs.close();
								pstmt = null;
								rs = null;								
								if(cnt == 0)
								{
									errCode = "VTCURFIN";
									errString = getErrorString("curr_code",errCode,userId);
									break;
								}
							}
						 
					 }
					 
					 
					  if(childNodeName.equalsIgnoreCase("cr_term"))
					 {
						 crTerm=genericUtility.getColumnValue("cr_term",dom);
						 System.out.println("@@-------crTerm : "+crTerm);
							if (crTerm !=null && crTerm.trim().length() > 0)	 
							{							
							 	sql = "select count(1) from crterm where cr_term = ? ";
								pstmt=conn.prepareStatement(sql);
								pstmt.setString(1,crTerm);
								rs = pstmt.executeQuery();
								if(rs.next())
								{
									cnt = rs.getInt(1);
								}
								pstmt.close();
								rs.close();
								pstmt = null;
								rs = null;								
								if(cnt == 0)
								{
									errCode = "VMCRTRMNF";
									errString = getErrorString("cr_term",errCode,userId);
									break;
								}
							}
						 
					 }
					 
					 
					 
					 if(childNodeName.equalsIgnoreCase("tax_class"))
					 {
						 taxClass=genericUtility.getColumnValue("tax_class",dom);
						 System.out.println("@@------taxClass : "+taxClass);
						 if (taxClass !=null && taxClass.trim().length() > 0)	
						 {
							 	sql = "select count(1) from taxclass where tax_class = ? ";
								pstmt=conn.prepareStatement(sql);
								pstmt.setString(1,taxClass);
								rs = pstmt.executeQuery();
								if(rs.next())
								{
									cnt = rs.getInt(1);
								}
								System.out.println("Count taxClass -----: "+cnt);
								pstmt.close();
								rs.close();
								pstmt = null;
								rs = null;								
								if(cnt == 0)
								{
									errCode = "VMTAXCLSNF";
									errString = getErrorString("tax_class",errCode,userId);
									break;
								}
						 }
					 }
					 if(childNodeName.equalsIgnoreCase("tax_env"))
					 {
						 taxENV=genericUtility.getColumnValue("tax_env",dom);
						 System.out.println("@@--------- taxENV : "+taxENV);
							
						 if (taxENV !=null && taxENV.trim().length() > 0)	
						 {
							 	sql = "select count(1) from taxenv where tax_env = ? ";
								pstmt=conn.prepareStatement(sql);
								pstmt.setString(1,taxENV);
								rs = pstmt.executeQuery();
								if(rs.next())
								{
									cnt = rs.getInt(1);
								}
								System.out.println("Count taxENV -----: "+cnt);
								pstmt.close();
								rs.close();
								pstmt = null;
								rs = null;								
								if(cnt == 0)
								{
									errCode = "VMTAXENVNF";
									errString = getErrorString("tax_env",errCode,userId);
									break;
								}
						 }
					 }
			
					
				 } //end for loop
											
			} //end switch
		
		} //end try
		catch(Exception e)
		{
			System.out.println("Exception ::"+e);
			e.printStackTrace();
			errString=e.getMessage();
            throw new ITMException(e);
		}
		finally
		{
			try
			{
				if(conn!=null)
				{
					if(rs != null )
					{
						rs.close();
						rs = null;
					}
					if(pstmt != null )pstmt.close();
					pstmt =null;
					conn.close();
				}
				conn = null;
			}
			catch(Exception d)
			{
			  d.printStackTrace();
			}
		}
		
		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
	{
		System.out.println("------------------ itemChanged called------------------");
		Document dom = null;
		Document dom1 = null;
		Document dom2 = null;
		String valueXmlString = "";
		try
		{   
			dom = parseString(xmlString);
			dom1 = parseString(xmlString1);
			dom2 = parseString(xmlString2);
			valueXmlString = itemChanged(dom,dom1,dom2,objContext,currentColumn,editFlag,xtraParams);
		}
		catch(Exception e)
		{
			System.out.println("Exception : [SiteLoanParty ][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
	{

		System.out.println("@@@@@@@ itemChanged called");
		StringBuffer valueXmlString = new StringBuffer();
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		Connection conn = null;
		PreparedStatement pstmt = null,pstmt1 = null;
		ResultSet rs = null,rs1 = null ;
		String childNodeName = null;
		GenericUtility genericUtility = GenericUtility.getInstance();
		ConnDriver connDriver = new ConnDriver();
		String sql="",sql1="";
		int currentFormNo =0;
		String columnValue="",siteCode="",salesPerson="",chgTerm="",chgUser="",siteCodePay="",siteCodeDescr="";
		String siteCodePayDescr="",salesPersonName="",PartyCode="",PartyName="",currcode="";
		int ctr=0;
		
		try
		{		
			conn = connDriver.getConnectDB("DriverITM");
			conn.setAutoCommit(false);
			connDriver=null;
			if(objContext != null && objContext.trim().length()>0)
			{
				currentFormNo = Integer.parseInt(objContext.trim());
			}
			valueXmlString = new StringBuffer("<?xml version=\"1.0\"?><Root><header><editFlag>");
			valueXmlString.append(editFlag).append("</editFlag></header>");
			chgTerm = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "chg_term");
			chgUser = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "chg_user");
			System.out.println("-------- currentFormNo : "+currentFormNo);
			switch(currentFormNo)
			{
	
				case 1 :
				parentNodeList = dom.getElementsByTagName("Detail1");
				parentNode = parentNodeList.item(0);
				childNodeList = parentNode.getChildNodes();
				ctr = 0; 
				valueXmlString.append("<Detail1>");
				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));
				System.out.println("[" + currentColumn + "] ==> '" + columnValue + "'");
				
			
				if( currentColumn.trim().equalsIgnoreCase( "itm_default" ) )
				{
					System.out.println("------------@@@@@@@@in itm_default@@@@@@@@@---------");
					Calendar currentDate = Calendar.getInstance();
					SimpleDateFormat simpleDateFormatObj = new SimpleDateFormat(genericUtility.getApplDateFormat());
					String systemDate = simpleDateFormatObj.format(currentDate.getTime());
					System.out.println("Now the date is :=>  " + systemDate);
						
					valueXmlString.append("<site_code>").append("").append("</site_code>");
					valueXmlString.append("<chg_date><![CDATA[").append(systemDate).append("]]></chg_date>\r\n");
					valueXmlString.append("<chg_term><![CDATA[").append(chgTerm).append("]]></chg_term>");
					valueXmlString.append("<chg_user><![CDATA[").append(chgUser).append("]]></chg_user>");
					
				}
			
				
				if((currentColumn.trim().equalsIgnoreCase("site_code")))
				{
					siteCode = genericUtility.getColumnValue("site_code",dom);
					System.out.println("site_code -----   :->> "+siteCode);
					if(siteCode != null && siteCode.trim().length()>0 )
					{
						sql = "SELECT DESCR FROM SITE WHERE SITE_CODE = ? ";
						pstmt= conn.prepareStatement(sql);
						pstmt.setString(1,siteCode);
						rs = pstmt.executeQuery();
						while(rs.next())
						{
							siteCodeDescr = rs.getString(1) == null ? "" : rs.getString(1);
						}
					rs.close();
					rs = null;
					pstmt.close();
					pstmt = null;
					
					valueXmlString.append("<site_descr>").append("<![CDATA[" + siteCodeDescr + "]]>").append("</site_descr>");
					
					System.out.println("siteCodeDescr---------- >> : "+siteCodeDescr);
					
					}
					else
					{
						valueXmlString.append("<site_descr>").append("<![CDATA[]]>").append("</site_descr>");
						
					}
				}
				
				else if((currentColumn.trim().equalsIgnoreCase("party_code")))
				{
				PartyCode = genericUtility.getColumnValue("party_code",dom);
					System.out.println("salesPerson----->> : "+PartyCode);
					if(PartyCode != null && PartyCode.trim().length()>0 )
					{
						sql = "select party_name from LOANPARTY where party_code = ? ";
						pstmt= conn.prepareStatement(sql);
						pstmt.setString(1,PartyCode);
						rs = pstmt.executeQuery();
						while(rs.next())
						{
							PartyName = rs.getString(1) == null ? "" : rs.getString(1);
						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;
						valueXmlString.append("<party_name>").append("<![CDATA[" + PartyName + "]]>").append("</party_name>");
						System.out.println("PartyName---------- >> : "+PartyName);
					}
					else
					{
						valueXmlString.append("<party_name>").append("<![CDATA[]]>").append("</party_name>");
					}
				}
				
				if((currentColumn.trim().equalsIgnoreCase("site_code__pay")))
				{
					siteCodePay = genericUtility.getColumnValue("site_code__pay",dom);
					System.out.println("site_code__pay -----   :->> "+siteCode);
					if(siteCodePay != null && siteCodePay.trim().length()>0 )
					{
						sql = "SELECT DESCR FROM SITE WHERE SITE_CODE = ? ";
						pstmt= conn.prepareStatement(sql);
						pstmt.setString(1,siteCodePay);
						rs = pstmt.executeQuery();
						while(rs.next())
						{
							siteCodePayDescr = rs.getString(1) == null ? "" : rs.getString(1);
						}
						
						// changes by deepak
						String cnt2 = null;
						String sql2 = "select fin_entity from site where site_code ='"+ siteCodePay +"'";
						System.out.println("deepak sitecodepay"+siteCodePay);
						 Statement st2 = conn.createStatement();
						 ResultSet rs2 = st2.executeQuery(sql2);
						 System.out.println("two2");
						 
						 if(rs2.next())
							{
								cnt2 = rs2.getString(1);
								System.out.println(cnt2);
								System.out.println("four4");
							}
						 
						 sql1 = "SELECT CURR_CODE FROM FINENT WHERE FIN_ENTITY = '"+ cnt2 +"'" ;
						 System.out.println("deepak cnt"+cnt2);
						 Statement st3 = conn.createStatement();
						 rs1 = st3.executeQuery(sql1);
							while(rs1.next())
							{
								currcode = rs1.getString(1) == null ? "" : rs1.getString(1);
								System.out.println("deepak currcode"+currcode);
							}
						 
						 
						
						
						// changes by deepak
						
						
						
						
					rs.close();
					rs = null;
					pstmt.close();
					pstmt = null;
					rs1.close();
					rs1 = null;
					st3.close();
					st3 = null;
					
					
					valueXmlString.append("<site_descr_pay>").append("<![CDATA[" + siteCodePayDescr + "]]>").append("</site_descr_pay>");
					valueXmlString.append("<curr_code>").append("<![CDATA[" + currcode + "]]>").append("</curr_code>");
					
					System.out.println("siteCodePayDescr---------- >> : "+siteCodePayDescr);
					System.out.println("currcode---------- >> : "+currcode);
					
					}
					else
					{
						valueXmlString.append("<site_descr_pay>").append("<![CDATA[]]>").append("</site_descr_pay>");
						valueXmlString.append("<curr_code>").append("<![CDATA[]]>").append("</curr_code>");
						
					}
				}
					valueXmlString.append("</Detail1>");
				}// end switch
			valueXmlString.append("</Root>");
		}
		catch(Exception e)
		{
			e.printStackTrace();
			System.out.println("Exception ::"+e.getMessage());
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if(conn!=null)
				{
					if(rs != null)
					{
						rs.close();
						rs = null;
					}
					if(pstmt != null)
					{
						pstmt.close();
						pstmt = null;
					}
					conn.close();
					conn = null;
				}
			}
			catch(Exception d)
			{
			  d.printStackTrace();
			}			
		}
		
		return valueXmlString.toString();
	}
	
	
	
}
