package ibase.webitm.ejb.sys;

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.util.ArrayList;

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 // added for ejb3
public class SiteRegNoIC extends ValidatorEJB implements SiteRegNoICLocal,SiteRegNoICRemote
{
	GenericUtility genericUtility = GenericUtility.getInstance(); 

	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);
			dom2 = parseString(xmlString2);
			System.out.println("@@@@@@@@  wfValData called");
			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
	{
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		int ctr=0,count=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 userId="";
		String siteCode="",effFromStr="",validUptoStr="",finEntity="",errCode="",errorType="",refCode="",regNo="";
		Timestamp  effFrom=null,validUpto=null;
		ArrayList<String> errList = new ArrayList<String>();
		ArrayList<String> errFields = new ArrayList<String>();
		
		StringBuffer errStringXml = new StringBuffer("<?xml version = \"1.0\"?> \r\n <Root> <Errors>");
		try
		{
			System.out.println("@@@@@@@@ wfvaldata called");
			conn = connDriver.getConnectDB("DriverITM");
			connDriver = null;
			userId = getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			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("ref_code") )
					{
						System.out.println("@@@@@ validation ref_code executed");
					
						refCode = genericUtility.getColumnValue("ref_code",dom);
						
					   if ( refCode == null || refCode.trim().length() == 0  )
				       {   
				    	   		errCode = "VMREFNONUL";
								errList.add(errCode);
								errFields.add(childNodeName.toLowerCase());
					   }
					   else
					   {   
						   sql = " SELECT count(1) FROM  GENCODES WHERE FLD_NAME = 'REF_CODE' and FLD_VALUE = ? ";
						   pstmt = conn.prepareStatement(sql);
							pstmt.setString( 1, refCode );
							rs = pstmt.executeQuery();
							if (rs.next())
							{
								cnt = rs.getInt(1);
							}
							rs.close();
							rs = null;
							pstmt.close();
							pstmt = null;

							if( cnt == 0 )
				            {		
								errCode = "VU_REFNO";
								errList.add(errCode);
								errFields.add(childNodeName.toLowerCase());
							}
						   
						   
						   refCode = genericUtility.getColumnValue("ref_code",dom);
						   siteCode = genericUtility.getColumnValue("site_code",dom);
						   finEntity = genericUtility.getColumnValue("fin_entity",dom);
						   System.out.println("@@@@@ for validation for primary ");
						   if( (!("E".equalsIgnoreCase(editFlag))) && refCode!= null && refCode.trim().length() > 0 &&  siteCode!= null && siteCode.trim().length() > 0 &&  finEntity!= null && finEntity.trim().length() > 0 )
						   {   
					    	   sql = " select count(1) from siteregno where site_code = ?  and fin_entity = ? and ref_code = ? ";
					    	   pstmt = conn.prepareStatement(sql);
								pstmt.setString( 1, siteCode );
								pstmt.setString( 2, finEntity );
								pstmt.setString( 3, refCode );
								rs = pstmt.executeQuery();
								if (rs.next())
								{
									cnt = rs.getInt(1);
								}

								rs.close();
								rs = null;
								pstmt.close();
								pstmt = null;

								if( cnt > 0 )
					            {		
									errCode = "VMDUPREC1";
									errList.add(errCode);
									errFields.add(childNodeName.toLowerCase());
								}
					       }
						   
					   }
					} 
					
					
					if(childNodeName.equalsIgnoreCase("site_code") )
					{
						System.out.println("@@@@@ validation site_code executed");
					
					   siteCode = genericUtility.getColumnValue("site_code",dom);
					   if ( siteCode != null && siteCode.trim().length() > 0  && !("99999".equalsIgnoreCase(siteCode)) )
				       {   
				    	   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);
							}

							rs.close();
							rs = null;
							pstmt.close();
							pstmt = null;

							if( cnt == 0 )
				            {		
								errCode = "VMSITE1";
								errList.add(errCode);
								errFields.add(childNodeName.toLowerCase());
							}
				       }
					   else
					   {  
							errCode = "VMSITECD1";
							errList.add(errCode);
							errFields.add(childNodeName.toLowerCase());
						}
											
					} 


					if(childNodeName.equalsIgnoreCase("fin_entity") )
					{
						System.out.println("@@@@@ validation fin_entity executed");
					
					   finEntity = genericUtility.getColumnValue("fin_entity",dom);
					   if ( finEntity != null && finEntity.trim().length() > 0  )
				       {   
				    	   sql = " select count(1) from finent where fin_entity = ? ";
				    	   pstmt = conn.prepareStatement(sql);
							pstmt.setString( 1, finEntity );
							rs = pstmt.executeQuery();
							if (rs.next())
							{
								cnt = rs.getInt(1);
							}

							rs.close();
							rs = null;
							pstmt.close();
							pstmt = null;

							if( cnt == 0 )
				            {		
									errCode = "VMFENTY1";
									errList.add(errCode);
									errFields.add(childNodeName.toLowerCase());
							}
				       }
					   else
					   {		
							errCode = "VMFINENT1 ";
							errList.add(errCode);
							errFields.add(childNodeName.toLowerCase());
					   }
					} 


					if(childNodeName.equalsIgnoreCase("reg_no") )
					{
						System.out.println("@@@@@ validation reg_no executed");
					
						regNo = genericUtility.getColumnValue("reg_no",dom);
					   if ( regNo == null || regNo.trim().length() == 0  )
				       {		
							errCode = "VMREGNONUL";
							errList.add(errCode);
							errFields.add(childNodeName.toLowerCase());
					   }
					} 



					
					if(childNodeName.equalsIgnoreCase("eff_from"))
					{
						System.out.println("@@@@@ date validation executed");
						
						effFromStr = genericUtility.getColumnValue("eff_from",dom);
						validUptoStr = genericUtility.getColumnValue("valid_upto",dom);
						System.out.println("@@@1 date validation effFromStr["+effFromStr+"]:::validUptoStr["+validUptoStr+"]");
						if ( ( effFromStr !=null && effFromStr.trim().length() > 0 ) || ( validUptoStr != null && validUptoStr.trim().length() > 0 ) )
						{
							if(  effFromStr ==null ||  effFromStr.trim().length() == 0  )
							 {
								errCode = "EFFDT1";
								errList.add(errCode);
								errFields.add(childNodeName.toLowerCase());
							 }
							else if(validUptoStr == null || validUptoStr.trim().length()==0)
							{
								errCode = "VTDATE26";
								errList.add(errCode);
								errFields.add(childNodeName.toLowerCase());
							}
							else
							{
								effFrom = Timestamp.valueOf(genericUtility.getValidDateString(effFromStr, genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat()) + " 00:00:00.0");
								validUpto = Timestamp.valueOf(genericUtility.getValidDateString(validUptoStr, genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat()) + " 00:00:00.0");
								if(effFrom.after(validUpto))
								{
									System.out.println("effFrom.after(validUpto");
									errCode = "VTDATE6";
									errList.add(errCode);
									errFields.add(childNodeName.toLowerCase());
								}	
							}
						}
					}
				} // end for
				break;	
			} //END switch
			
			

			int errListSize = errList.size();
			count = 0;
			String errFldName = null;
			if(errList != null && errListSize > 0)
			{
				for(count = 0; count < errListSize; count ++)
				{
					errCode = errList.get(count);
					errFldName = errFields.get(count);
					System.out.println("errCode .........." + errCode);
					errString = getErrorString(errFldName, errCode, userId);
					errorType = errorType(conn , errCode);
					if(errString.length() > 0)
					{
						String bifurErrString = errString.substring(errString.indexOf("<Errors>") + 8, errString.indexOf("<trace>"));
						bifurErrString = bifurErrString + errString.substring(errString.indexOf("</trace>") + 8, errString.indexOf("</Errors>"));
						errStringXml.append(bifurErrString);
						errString = "";
					}
					if(errorType.equalsIgnoreCase("E"))
					{
						break;
					}
				}
				errList.clear();
				errList = null;
				errFields.clear();
				errFields = null;
				errStringXml.append("</Errors> </Root> \r\n");
			}
			else
			{
				errStringXml = new StringBuffer("");
			}
		
			
		}//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);

		errString = errStringXml.toString();
		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);
			dom1 = parseString(xmlString1);
			dom2 = parseString(xmlString2);
			valueXmlString = itemChanged(dom,dom1,dom2,objContext,currentColumn,editFlag,xtraParams);
		}
		catch(Exception e)
		{
			System.out.println("Exception : [TrainingEJB][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;
		ResultSet rs = null;
		String childNodeName = null;
		GenericUtility genericUtility = GenericUtility.getInstance();
		ConnDriver connDriver = new ConnDriver();
		String sql="";
		int currentFormNo =0;
		String columnValue="";
		int ctr=0;

		String siteCode="",finEntity="", finEntityDescr="",refCode="";
		
		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>");

			System.out.println("**********ITEMCHANGE FOR CASE"+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("@@@@@ itm_default item change called");
					siteCode = genericUtility.getColumnValue("site_code",dom);
					//siteCode = genericUtility.getValueFromXTRA_PARAMS( xtraParams, "loginSiteCode" );
					if(siteCode != null && siteCode.trim().length() > 0)
					{
						sql = "	Select fin_entity from site where site_code = ? ";
						pstmt = conn.prepareStatement(sql);
						pstmt.setString( 1, siteCode );
						rs = pstmt.executeQuery();
						if (rs.next())
						{
							finEntity = rs.getString(1);
						}

						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;

					}
					//valueXmlString.append( "<site_code><![CDATA[" ).append(siteCode==null?"":siteCode).append( "]]></site_code>\r\n" );
					System.out.println("@@@@@ finEntity["+finEntity+"]");
					if ("99999".equalsIgnoreCase(siteCode))
					{			
						//fin_entity = genericUtility.getColumnValue("fin_entity",dom);
						valueXmlString.append( "<fin_entity  protect=\"0\" ><![CDATA[" ).append(finEntity==null?"":finEntity).append( "]]></fin_entity>\r\n" );
					}
					else	
					{	
						
						if( finEntity != null && finEntity.trim().length() > 0 )		
						{
							sql = "	select descr from finent where fin_entity = ? ";
							pstmt = conn.prepareStatement(sql);
							pstmt.setString( 1, finEntity );
							rs = pstmt.executeQuery();
							if (rs.next())
							{
								finEntityDescr = rs.getString(1);
							}
							rs.close();
							rs = null;
							pstmt.close();
							pstmt = null;
						}
						
						System.out.println("@@@@@ finEntityDescr["+finEntityDescr+"]");
						
						valueXmlString.append( "<fin_entity  protect=\"1\" ><![CDATA[" ).append(finEntity==null?"":finEntity).append( "]]></fin_entity>\r\n" );
						valueXmlString.append( "<finent_descr  protect=\"1\" ><![CDATA[" ).append(finEntityDescr==null?"":finEntityDescr).append( "]]></finent_descr>\r\n" );

					}
					
					refCode = genericUtility.getColumnValue("ref_code",dom);
					valueXmlString.append( "<ref_code  protect=\"0\" ><![CDATA[" ).append(refCode==null?"":refCode).append( "]]></ref_code>\r\n" );
				}

				if( currentColumn.trim().equalsIgnoreCase( "itm_defaultedit" ) )
				{
					System.out.println("@@@@@ itm_defaultedit item change called");
					finEntity = genericUtility.getColumnValue("fin_entity",dom);
					valueXmlString.append( "<fin_entity  protect=\"0\" ><![CDATA[" ).append(finEntity==null?"":finEntity).append( "]]></fin_entity>\r\n" );
				}

				if( currentColumn.trim().equalsIgnoreCase( "fin_entity" ) )
				{
					System.out.println("@@@@@ fin_entity item change called");
					finEntity = genericUtility.getColumnValue("fin_entity",dom);
					if( finEntity != null && finEntity.trim().length() > 0 )		
					{
						sql = "	select descr from finent where fin_entity = ? ";
						pstmt = conn.prepareStatement(sql);
						pstmt.setString( 1, finEntity );
						rs = pstmt.executeQuery();
						if (rs.next())
						{
							finEntityDescr = rs.getString(1);
						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;
					}
					valueXmlString.append( "<finent_descr  protect=\"1\" ><![CDATA[" ).append(finEntityDescr==null?"":finEntityDescr).append( "]]></finent_descr>\r\n" );
				}

				
				valueXmlString.append("</Detail1>");
				break;

			}
			valueXmlString.append("</Root>");
			
			
		}// end try
		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();
	}//End of itemChanged	 

	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();
			if(rs.next())
			{
				msgType = rs.getString("MSG_TYPE");
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;
		}
		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;
	}


}



