/********************************************************
	Title : SundryTransferIC[FI3LFRA001]
	Date  : 08/04/14
	Developer: Chandrashekar

 ********************************************************/
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.text.SimpleDateFormat;
import java.util.*;
import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.ejb.Stateless; 
@Stateless 

public class SundryTransferIC extends ValidatorEJB implements SundryTransferICLocal, SundryTransferICRemote
{
	GenericUtility genericUtility = GenericUtility.getInstance();

	public String wfValData(String xmlString, String xmlString1, String xmlString2, String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		String errString = "";
		Document dom = null;
		Document dom1 = null;
		Document dom2 = null;
		try
		{
			if (xmlString != null && xmlString.trim().length() > 0 )
			{
				dom = parseString(xmlString);
				System.out.println("xmlString["+xmlString+"]");
			}
			if (xmlString1 != null && xmlString1.trim().length() > 0 )
			{
				dom1 = parseString(xmlString1);
				System.out.println("xmlString1["+xmlString1+"]");
			}
			if (xmlString2 != null && xmlString2.trim().length() > 0 )
			{
				dom2 = parseString(xmlString2);
				System.out.println("xmlString2["+xmlString2+"]");
				
			}
			
			errString = wfValData(dom, dom1, dom2, objContext, editFlag, xtraParams);
		}
		catch(Exception e)
		{
			System.out.println("Exception : [SundryTransferIC][wfValData( String, String )] :==>\n" + e.getMessage());
			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 childNodeName = null;
			String errString = "";
			String errCode = "";
			String userId = "";
			String sql = "";
			String errorType = "";
			int cnt = 0;
			int ctr=0;
			int childNodeListLength;
			NodeList parentNodeList = null;
			NodeList childNodeList = null;	
			Node parentNode = null;
			Node childNode = null;
			ArrayList<String> errList = new ArrayList<String>();
			ArrayList<String> errFields = new ArrayList<String>();
			Connection conn = null;
			PreparedStatement pstmt = null ;
			ResultSet rs = null;
			ConnDriver connDriver = new ConnDriver();
			StringBuffer errStringXml = new StringBuffer("<?xml version = \"1.0\"?> \r\n <Root> <Errors>");
			
			int currentFormNo =0,count=0;
			String accPeriodFr="",acctPrdTo="",siteCode="",finEntity="",sundryCodeFr="",sundryCodeTo="",sundryType="";
			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("fin_entity"))
				    	{
							finEntity = genericUtility.getColumnValue("fin_entity", dom);
							if(finEntity == null || (finEntity.length() == 0))
							{
								errList.add("VMFINENT1 ");
								errFields.add(childNodeName.toLowerCase());
							}
							if(finEntity != null && finEntity.trim().length() > 0)
							{
								sql = " select count(*) from finent where fin_entity = ?  ";
								pstmt =  conn.prepareStatement(sql);
								pstmt.setString(1,finEntity);
								rs = pstmt.executeQuery();
								if(rs.next())
								{
									count =  rs.getInt(1);
								}
								if(count == 0) 
								{
									errCode = "VMFINENTM2";
									errList.add(errCode);
									errFields.add(childNodeName.toLowerCase());	
								}
								rs.close();
								rs = null;
								pstmt.close();
								pstmt = null;
							}
						}
						else if(childNodeName.equalsIgnoreCase("sundry_code__fr"))
				    	{
							sundryCodeFr = genericUtility.getColumnValue("sundry_code__fr", dom);
							sundryType = genericUtility.getColumnValue("sundry_type", dom);
							System.out.println("sundryTypeFr["+sundryType+"]");
							if(sundryCodeFr == null || (sundryCodeFr.length() == 0))
							{
								errList.add("VTSUNCDFR");
								errFields.add(childNodeName.toLowerCase());
							}
							else
							{	if("00".equalsIgnoreCase(sundryCodeFr))
								{
								
								}
								else
								{	
									if("S".equalsIgnoreCase(sundryType))
								    {
										errCode = isExist("sundrybal","sundry_code",sundryCodeFr,conn);
										if( "FALSE".equalsIgnoreCase(errCode ))		
										{
											errCode = "VMSUNDFR1";
											errList.add(errCode);
											errFields.add(childNodeName.toLowerCase());
										}
								    }
									/*if("S".equalsIgnoreCase(sundryType))
								    {
										errCode = isExist("supplier","supp_code",sundryCodeFr,conn);
										if( "FALSE".equalsIgnoreCase(errCode ))		
										{
											errCode = "VMSUNCDFR";
											errList.add(errCode);
											errFields.add(childNodeName.toLowerCase());
										}
								    }*/
									else if("E".equalsIgnoreCase(sundryType))
									{
										errCode = isExist("employee","emp_code",sundryCodeFr,conn);
										if( "FALSE".equalsIgnoreCase(errCode ))		
										{
											errCode = "VMSUNCDFR";
											errList.add(errCode);
											errFields.add(childNodeName.toLowerCase());
										}
									}
									else if("C".equalsIgnoreCase(sundryType))
									{
										errCode = isExist("customer","cust_code",sundryCodeFr,conn);
										if( "FALSE".equalsIgnoreCase(errCode ))		
										{
											errCode = "VMSUNCDFR";
											errList.add(errCode);
											errFields.add(childNodeName.toLowerCase());
										}
									}
									else if("T".equalsIgnoreCase(sundryType))
									{
										errCode = isExist("transporter","tran_code",sundryCodeFr,conn);
										if( "FALSE".equalsIgnoreCase(errCode ))		
										{
											errCode = "VMSUNCDFR";
											errList.add(errCode);
											errFields.add(childNodeName.toLowerCase());
										}
									}
									else if("P".equalsIgnoreCase(sundryType))
									{
										errCode = isExist("sales_pers","sales_pers",sundryCodeFr,conn);
										if( "FALSE".equalsIgnoreCase(errCode ))		
										{
											errCode = "VMSUNCDFR";
											errList.add(errCode);
											errFields.add(childNodeName.toLowerCase());
										}
									}							
									else if("L".equalsIgnoreCase(sundryType))
									{
										errCode = isExist("loanparty","party_code",sundryCodeFr,conn);
										if( "FALSE".equalsIgnoreCase(errCode ))		
										{
											errCode = "VMSUNCDFR";
											errList.add(errCode);
											errFields.add(childNodeName.toLowerCase());
										}
									}
									else if("X".equalsIgnoreCase(sundryType))
									{
										errCode = isExist("tax_authority","tauth_code",sundryCodeFr,conn);
										if( "FALSE".equalsIgnoreCase(errCode ))		
										{
											errCode = "VMSUNCDFR";
											errList.add(errCode);
											errFields.add(childNodeName.toLowerCase());
										}
									}
									else if("B".equalsIgnoreCase(sundryType))
									{
										errCode = isExist("bank","bank_code",sundryCodeFr,conn);
										if( "FALSE".equalsIgnoreCase(errCode ))		
										{
											errCode = "VMSUNCDFR";
											errList.add(errCode);
											errFields.add(childNodeName.toLowerCase());
										}
									}
									else if("R".equalsIgnoreCase(sundryType))
									{
										errCode = isExist("strg_customer","sc_code",sundryCodeFr,conn);
										if( "FALSE".equalsIgnoreCase(errCode ))		
										{
											errCode = "VMSUNCDFR";
											errList.add(errCode);
											errFields.add(childNodeName.toLowerCase());
										}
									}
								}
							}
						}
						else if(childNodeName.equalsIgnoreCase("sundry_code__to"))
				    	{
							sundryCodeTo = genericUtility.getColumnValue("sundry_code__to", dom);
							sundryType = genericUtility.getColumnValue("sundry_type", dom);
							System.out.println("sundryTypeTo["+sundryType+"]");
							if(sundryCodeTo == null || (sundryCodeTo.length() == 0))
							{
								errList.add("VTSUNCDTO");
								errFields.add(childNodeName.toLowerCase());
							}
							else
							{	if("zz".equalsIgnoreCase(sundryCodeTo))
								{
								
								}
								else
								{	if("S".equalsIgnoreCase(sundryType))
									{
										errCode = isExist("sundrybal","sundry_code",sundryCodeTo,conn);
										if( "FALSE".equalsIgnoreCase(errCode ))		
										{
											errCode = "VMSUNDTO1";
											errList.add(errCode);
											errFields.add(childNodeName.toLowerCase());
										}
									}
									/*if("S".equalsIgnoreCase(sundryType))
								    {
										errCode = isExist("supplier","supp_code",sundryCodeTo,conn);
										if( "FALSE".equalsIgnoreCase(errCode ))		
										{
											errCode = "VMSUNCDTO";
											errList.add(errCode);
											errFields.add(childNodeName.toLowerCase());
										}
								    }*/
									else if("E".equalsIgnoreCase(sundryType))
									{
										errCode = isExist("employee","emp_code",sundryCodeTo,conn);
										if( "FALSE".equalsIgnoreCase(errCode ))		
										{
											errCode = "VMSUNCDTO";
											errList.add(errCode);
											errFields.add(childNodeName.toLowerCase());
										}
									}
									else if("C".equalsIgnoreCase(sundryType))
									{
										errCode = isExist("customer","cust_code",sundryCodeTo,conn);
										if( "FALSE".equalsIgnoreCase(errCode ))		
										{
											errCode = "VMSUNCDTO";
											errList.add(errCode);
											errFields.add(childNodeName.toLowerCase());
										}
									}
									else if("T".equalsIgnoreCase(sundryType))
									{
										errCode = isExist("transporter","tran_code",sundryCodeTo,conn);
										if( "FALSE".equalsIgnoreCase(errCode ))		
										{
											errCode = "VMSUNCDTO";
											errList.add(errCode);
											errFields.add(childNodeName.toLowerCase());
										}
									}
									else if("P".equalsIgnoreCase(sundryType))
									{
										errCode = isExist("sales_pers","sales_pers",sundryCodeTo,conn);
										if( "FALSE".equalsIgnoreCase(errCode ))		
										{
											errCode = "VMSUNCDTO";
											errList.add(errCode);
											errFields.add(childNodeName.toLowerCase());
										}
									}							
									else if("L".equalsIgnoreCase(sundryType))
									{
										errCode = isExist("loanparty","party_code",sundryCodeTo,conn);
										if( "FALSE".equalsIgnoreCase(errCode ))		
										{
											errCode = "VMSUNCDTO";
											errList.add(errCode);
											errFields.add(childNodeName.toLowerCase());
										}
									}
									else if("X".equalsIgnoreCase(sundryType))
									{
										errCode = isExist("tax_authority","tauth_code",sundryCodeTo,conn);
										if( "FALSE".equalsIgnoreCase(errCode ))		
										{
											errCode = "VMSUNCDTO";
											errList.add(errCode);
											errFields.add(childNodeName.toLowerCase());
										}
									}
									else if("B".equalsIgnoreCase(sundryType))
									{
										errCode = isExist("bank","bank_code",sundryCodeTo,conn);
										if( "FALSE".equalsIgnoreCase(errCode ))		
										{
											errCode = "VMSUNCDTO";
											errList.add(errCode);
											errFields.add(childNodeName.toLowerCase());
										}
									}
									else if("R".equalsIgnoreCase(sundryType))
									{
										errCode = isExist("strg_customer","sc_code",sundryCodeTo,conn);
										if( "FALSE".equalsIgnoreCase(errCode ))		
										{
											errCode = "VMSUNCDTO";
											errList.add(errCode);
											errFields.add(childNodeName.toLowerCase());
										}
									}
									
								
								}
							}
						}
						else if(childNodeName.equalsIgnoreCase("acct_prd__fr"))
						{    
							accPeriodFr = checkNull(genericUtility.getColumnValue("acct_prd__fr", dom));
							acctPrdTo = checkNull(genericUtility.getColumnValue("acct_prd__to", dom));
							if(accPeriodFr == null || (accPeriodFr.length() == 0))
							{
								errList.add("VMINVPRDFR");
								errFields.add(childNodeName.toLowerCase());
							}
							if(accPeriodFr != null && accPeriodFr.trim().length() > 0)
							{
								sql = "select count(*) as count from acctprd where code =?";
								pstmt =  conn.prepareStatement(sql);
								pstmt.setString(1,accPeriodFr);
								rs = pstmt.executeQuery();
								if(rs.next())
								{   
									cnt = rs.getInt(1);
								}
								rs.close();
								rs = null;
								pstmt.close(); 
								pstmt = null;

								if( cnt == 0 )
								{
									errCode = "PRDCODE1";
									errList.add(errCode);
									errFields.add(childNodeName.toLowerCase());
								}
							}	
					}
	
				}// end for
					break;  // case 1 end
				}		
				int errListSize = errList.size();
				cnt = 0;
				String errFldName = null;
				if(errList != null && errListSize > 0)
				{
					for(cnt = 0; cnt < errListSize; cnt ++)
					{
						errCode = errList.get(cnt);
						errFldName = errFields.get(cnt);
						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("");
				}
			
		}
			catch(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();
					throw new ITMException(d);
				}
			}
			errString = errStringXml.toString();
			return errString;
		}

	//end of validation

	// method for item change
	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 = "";
		System.out.println("xmlString............."+xmlString);
		System.out.println("xmlString1............"+xmlString);
		System.out.println("xmlString2............"+xmlString);
		try
		{   
			if(xmlString != null && xmlString.trim().length() > 0)
			{
				dom = parseString(xmlString);
			}
			if(xmlString1 != null && xmlString1.trim().length() > 0)
			{
				dom1 = parseString(xmlString1);
			}
			if(xmlString2 != null && xmlString2.trim().length() > 0)
			{
				dom2 = parseString(xmlString2);
			}
			valueXmlString = itemChanged(dom, dom1, dom2, objContext, currentColumn, editFlag, xtraParams);
		}
		catch(Exception e)
		{
			System.out.println("Exception : [SundryTransferIC][itemChanged( String, String )] :==>\n" + e.getMessage());
			throw new ITMException(e);
		}
		return valueXmlString;
	}


	// method for item change
	public String itemChanged(Document dom, Document dom1, Document dom2, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException, ITMException
	{
	String childNodeName = null;
	String sql = "";
	StringBuffer valueXmlString = new StringBuffer();
	int ctr = 0;
	NodeList parentNodeList = null;
	NodeList childNodeList = null;
	Node parentNode = null;
	Node childNode = null;
	Connection conn = null;
	PreparedStatement pstmt = null;
	ResultSet rs = null ;
	GenericUtility genericUtility = GenericUtility.getInstance();
	ConnDriver connDriver = new ConnDriver();
	
	int currentFormNo =0;
	String columnValue="",acctPrdFr="",acctPrdTo="";
	
	
	Timestamp toDate=null;
	java.util.Date newDate=null;
	
	
	try
	{
		Calendar currentDate = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getApplDateFormat());
		String sysDate = sdf.format(currentDate.getTime());
		System.out.println("Now the date is :=>  " + sysDate);
		
		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("acct_prd__fr"))
			{
				acctPrdFr = checkNull(genericUtility.getColumnValue("acct_prd__fr", dom));
				
				sql = "select to_date from acctprd where code = ?";
				pstmt =  conn.prepareStatement(sql);
				pstmt.setString(1,acctPrdFr);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					toDate =  rs.getTimestamp("to_date");
					
				}
				rs.close();
				rs = null;
				pstmt.close(); 
				pstmt = null;
				if(toDate != null)
				{		
					newDate =  (java.util.Date ) relativeDate(toDate, 1);								
					sql = "select code from acctprd  where fr_date = ?";
					pstmt =  conn.prepareStatement(sql);				
					pstmt.setDate(1, new java.sql.Date(newDate.getTime()));
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						acctPrdTo =  rs.getString("code");
						
					}
					rs.close();
					rs = null;
					pstmt.close(); 
					pstmt = null;					
				}
				valueXmlString.append("<acct_prd__to>").append("<![CDATA["+acctPrdTo+"]]>").append("</acct_prd__to>");
			}
			
			
			

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

				}	
		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();
	}
	
	private String checkNull(String input) 
	{
		if(input == null)
		{
			input = "";
		}
		return input;
	}
	
	public static java.util.Date relativeDate(java.util.Date date, int days) 
	{
		java.util.Date calculatedDate = null;
		if (date != null) 
		{
			final GregorianCalendar calendar = new GregorianCalendar();
			calendar.setTime(date);
			calendar.add(Calendar.DATE,days);
			calculatedDate = new java.util.Date(calendar.getTime().getTime());
		}		
		return calculatedDate;
	}
	private String isExist(String table, String field, String value,Connection conn) throws SQLException
	{
		String sql = "",retStr="";
		PreparedStatement pstmt = null;
		ResultSet rs = null ;
		int cnt=0;

		sql = " SELECT COUNT(1) FROM "+ table + " WHERE " + field + " = ? ";
		pstmt =  conn.prepareStatement(sql);
		pstmt.setString(1,value);
		rs = pstmt.executeQuery();
		if(rs.next())
		{
			cnt = rs.getInt(1);
		}
		rs.close();
		rs = null;
		pstmt.close(); 
		pstmt = null;
		if( cnt > 0)
		{
			retStr = "TRUE";
		}
		if( cnt == 0 )
		{
			retStr = "FALSE";
		}
		System.out.println("@@@@ isexist["+value+"]:::["+retStr+"]:::["+cnt+"]");
		return retStr;
	}
	
	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;
	}



}	
