/********************************************************
	Title : StateIC	
	Date  : 07/10/2014
	Developer: Priyanka Shinde
 ********************************************************/

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.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import javax.ejb.Stateless;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

@Stateless
public class StateIC extends ValidatorEJB implements StateICLocal, StateICRemote 
{
	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
		{
			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)
		{
			throw new ITMException(e);
		}
		return(errString);
	}

//	@SuppressWarnings("null")
	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;
		int childNodeListLength;
		int currentFormNo = 0;		
		String stateCode = "";//
		String priceList="";
		String priceListClg="";
		long stateCnt=0;
		String countCode = "";
		String errorType = "";
		String childNodeName = null;
		String errString = "";
		String errCode = "";
		String sql = "";		
		String errFldName = "";
		String userId = "";
		String keyFlag="";
		long cnt = 0;	
		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();
		String regCode="",descr="",	validUpto="",regDate="";
		SimpleDateFormat simpleDateFormat1 = null;
		java.sql.Timestamp currDate = null;
		String currAppdate ="";
		Timestamp validDate=null,registerDate=null;
		StringBuffer errStringXml = new StringBuffer("<?xml version = \"1.0\"?> \r\n <Root> <Errors>"); 
		try
		{
			simpleDateFormat1 = new SimpleDateFormat(genericUtility.getApplDateFormat());
			currDate = new java.sql.Timestamp(System.currentTimeMillis()) ;
			currAppdate = new SimpleDateFormat(genericUtility.getApplDateFormat()).format(currDate);
			conn = connDriver.getConnectDB("DriverITM");
			if (objContext != null && objContext.trim().length() > 0)
			{
				currentFormNo = Integer.parseInt(objContext);
				System.out.println("Priyanka testing : currentFormNo :"+currentFormNo);
			}
			
	
			switch (currentFormNo)
			{
			 case 1:
				System.out.println("Priyanka testing case 1 for validation ");
	
			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("state_code"))
				{
					
					sql = "select key_flag from transetup where tran_window = 'w_state'";
					pstmt = conn.prepareStatement(sql);
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						keyFlag = rs.getString(1)==null ? "M" : rs.getString(1).trim();
					}
					rs.close();
					rs = null;
					pstmt.close();
					pstmt = null;
					
					if(keyFlag.equalsIgnoreCase("M"))
					{
						stateCode = genericUtility.getColumnValue("state_code", dom);
						if(stateCode==null ||stateCode.trim().length()==0)
						{
							errCode = "VESTATCD1";
							errList.add(errCode);
							errFields.add(childNodeName.toLowerCase());
							//break;
						}
											
						else
						{
							if(editFlag.equals("A"))
							{
								sql="select count(*) from state where state_code = ?";
								pstmt=conn.prepareStatement(sql);
								pstmt.setString(1, stateCode);
								rs=pstmt.executeQuery();
								if(rs.next())
								{
									stateCnt=rs.getInt(1);
									
								}
								rs.close();
								rs = null;
								pstmt.close();
								pstmt = null;
								if(stateCnt>0)
								{
									errCode = "VMDUPL1";
									errList.add(errCode);
									errFields.add(childNodeName.toLowerCase());
									//break;
								}
							}
					    }
					
					}
				}
			
				
				else if(childNodeName.equalsIgnoreCase("count_code"))  
				{
					countCode = genericUtility.getColumnValue("count_code", dom);
					
					if(countCode==null ||countCode.trim().length()==0)
					{
						errCode = "VTCOUTNULL";
						errList.add(errCode);
						errFields.add(childNodeName.toLowerCase());
						//break;
					}
					else
					{
						sql = "select count(*) from country where count_code =?";
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1, countCode);
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							cnt = rs.getInt(1);
							if(cnt == 0) 
							{
								errCode = "VTCONTCD1";
								errList.add(errCode);
								errFields.add(childNodeName.toLowerCase());
								//break;
							}									
						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;
					}
										
				}
				
	
				else if(childNodeName.equalsIgnoreCase("descr")) 
				{
					descr = genericUtility.getColumnValue("descr", dom);
					if(descr == null || descr.trim().length() == 0)
					{
						errCode = "VTDESC1";
						errList.add(errCode);
						errFields.add(childNodeName.toLowerCase());
						//break;
					}
				}
				
				else if(childNodeName.equalsIgnoreCase("price_list"))
				{
					priceList = genericUtility.getColumnValue("price_list", dom);			
					System.out.println("<<<<<<+"+priceList+"+>>>>>>>"+priceList);	
				
					sql = "select count(1) from pricelist where price_list = ?";
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, priceList);
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						cnt = rs.getInt(1);
						if(cnt == 0) 
						{
							errCode = "VTPLIST1";
							errList.add(errCode);
							errFields.add(childNodeName.toLowerCase());
						}									
					}
					rs.close();
					rs = null;
					pstmt.close();
					pstmt = null;
				}
					
				
				else if(childNodeName.equalsIgnoreCase("price_list__clg"))
				{
					priceListClg = genericUtility.getColumnValue("price_list__clg", dom);
					
					sql = "select count(1) from pricelist where price_list = ?";
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, priceListClg);
					rs = pstmt.executeQuery();
						if(rs.next())
						{
							cnt = rs.getInt(1);
							if(cnt == 0) 
							{
								errCode = "VTPLIST1";
								errList.add(errCode);
								errFields.add(childNodeName.toLowerCase());
							}									
						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;
				}
		
			
			}
						
			     break;
							
		              case 2:
							parentNodeList = dom.getElementsByTagName("Detail2");
							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("reg_code"))
								{
									
									regCode = genericUtility.getColumnValue("reg_code", dom);
									if(regCode==null || regCode.trim().length()==0)
									{
										errCode = "VTRCODNULL";
										errList.add(errCode);
										errFields.add(childNodeName.toLowerCase());
										//break;
									}
									else
									{
										sql=" select count(*) from reg_requirements where reg_code=?";
										pstmt = conn.prepareStatement(sql);
									    pstmt.setString(1, regCode);
										rs = pstmt.executeQuery();
										if(rs.next())
										{
												cnt=rs.getInt(1);						
										}
										rs.close();
										rs = null;
										pstmt.close();
										pstmt = null;							
										
										if(cnt==0)
										{
											errCode = "VTRCODEXT";
											errList.add(errCode);
											errFields.add(childNodeName.toLowerCase());
											//break;
										}
										
										
									}
									
								}
								 else if(childNodeName.equalsIgnoreCase("reg_date"))
								 {
									 regDate = genericUtility.getColumnValue("reg_date", dom);										
									 System.out.println(">>>>>>>>>>>regDate===="+regDate);
									 
									 if(regDate==null || regDate.trim().length()==0)
									 {
										 	errCode = "VTREGNULL";
											errList.add(errCode);
											errFields.add(childNodeName.toLowerCase());
											//break;
									 }								
								
								 }
									
								 else if(childNodeName.equalsIgnoreCase("valid_upto"))
								 {			
									 validUpto = genericUtility.getColumnValue("valid_upto", dom);		
									 regDate = genericUtility.getColumnValue("reg_date", dom);	
									 System.out.println(">>>>>>>>>>>validUpto===="+validUpto);
									 if(validUpto==null || validUpto.trim().length()==0)
									 {
										 errCode = "VTVALNULL";
											errList.add(errCode);
											errFields.add(childNodeName.toLowerCase());
											//break;
									 }
									 else
									 {
										 if(regDate!=null && regDate.trim().length()>0)
										 {
											     registerDate = Timestamp.valueOf(genericUtility.getValidDateString(regDate, genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat()) + " 00:00:00.0");
												 validDate = Timestamp.valueOf(genericUtility.getValidDateString(validUpto, genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat()) + " 00:00:00.0");
											   
												 if(validDate.equals(registerDate)||validDate.compareTo(registerDate)<0)
											    {
											    	errCode = "VTVALREGDT";
													errList.add(errCode);
													errFields.add(childNodeName.toLowerCase());
													break;
											    }
										 }
										
									 }							
									
								 }							
							
							} 						
			}
				
			
			int errListSize = errList.size();
			cnt = 0;
			if(errList != null && errListSize > 0)
			{
				for(cnt = 0; cnt < errListSize; cnt ++)
				{
					errCode = errList.get((int) 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;
	}

	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);
			if(xmlString2.trim().length() > 0 )
			{
				dom2 = parseString(xmlString2);
			}
			valueXmlString = itemChanged(dom, dom1, dom2, objContext, currentColumn, editFlag, xtraParams);
		}
		catch(Exception e)
		{
			System.out.println("Exception : [StateIC][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
	{
		int ctr = 0;
		
		StringBuffer valueXmlString = new StringBuffer();
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		String childNodeName = null;
		String regCode="";
		String regDescr="";
		String countCode = "";
		String countDescr="";		
		String sql = "";		
		int childNodeListLength = 0;
		Connection conn = null;
		PreparedStatement pstmt = null;		
		ResultSet rs = null ;
			
		int currentFormNo = 0;
		ConnDriver connDriver = new ConnDriver();
		try
		{   
			conn = connDriver.getConnectDB("DriverITM");
			conn.setAutoCommit(false);
			connDriver = null;
			
			
			if ((objContext != null) && (objContext.trim().length() > 0))
			{
				currentFormNo = Integer.parseInt(objContext);
				System.out.println("Priyanka itemchanged 1 currentFormNo : "+currentFormNo); 
			}
			valueXmlString = new StringBuffer("<?xml version = \"1.0\"?> <Root> <header> <editFlag>");
			valueXmlString.append(editFlag).append("</editFlag> </header>");
			switch (currentFormNo)
			{
			  case 1:
				System.out.println("State itemchanged case 1");
				parentNodeList = dom.getElementsByTagName("Detail1");
				parentNode = parentNodeList.item(0);
				childNodeList = parentNode.getChildNodes();
				valueXmlString.append("<Detail1>");
				childNodeListLength = childNodeList.getLength();
				do
				{
					childNode = childNodeList.item(ctr);
					childNodeName = childNode.getNodeName();
					if (childNodeName.equals(currentColumn))
					{
						childNode.getFirstChild();
					}

					ctr++;
				}
				while ((ctr < childNodeListLength) && (!childNodeName.equals(currentColumn)));
					
			
			if(currentColumn.trim().equalsIgnoreCase("count_code"))
			{
				countCode = genericUtility.getColumnValue("count_code", dom);
				sql="select descr from country where count_code = ?";
				pstmt=conn.prepareStatement(sql);
				pstmt.setString(1, countCode);
				rs=pstmt.executeQuery();
				if(rs.next())
				{
					countDescr=checkNull(rs.getString("descr"));
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;
				System.out.println("Country Description====>"+ countDescr);
			
				if(countDescr == null)
				{
					valueXmlString.append("<country_descr>").append("<![CDATA["+""+"]]>").append("</country_descr>");
				}
				else
				{
					valueXmlString.append("<country_descr>").append("<![CDATA[" +  countDescr + "]]>").append("</country_descr>");
				}
																			
			}	
			
			valueXmlString.append("</Detail1>");
			break;

			
		 case 2:

			System.out.println("State itemchanged case 2");
			parentNodeList = dom.getElementsByTagName("Detail2");
			parentNode = parentNodeList.item(0);
			childNodeList = parentNode.getChildNodes();
			valueXmlString.append("<Detail2>");
			childNodeListLength = childNodeList.getLength();
			do
			{
				childNode = childNodeList.item(ctr);
				childNodeName = childNode.getNodeName();
				if (childNodeName.equals(currentColumn))
				{
					childNode.getFirstChild();
				}

				ctr++;
			}
			while ((ctr < childNodeListLength) && (!childNodeName.equals(currentColumn)));
			System.out.println("CURRENT COLUMN Case 2 State *******["+currentColumn+"]");
						
			if (currentColumn.trim().equalsIgnoreCase("reg_code"))
			{
				System.out.println("reg_code========itemChanged");
				regCode=genericUtility.getColumnValue("reg_code", dom);
				sql="select descr from reg_requirements where reg_code=?";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, regCode);
				
				rs = pstmt.executeQuery();
				if (rs.next())
				{
					regDescr = checkNull(rs.getString("descr"));					
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;
				System.out.println("Reg Code description:=="+regDescr);
				
				if(regDescr == null)
				{
					valueXmlString.append("<descr>").append("<![CDATA["+""+"]]>").append("</descr>");
				}
				else
				{					
					valueXmlString.append("<descr>").append("<![CDATA["+regDescr+"]]>").append("</descr>");

				}
				
			}
			valueXmlString.append("</Detail2>");
			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(pstmt != null)
						pstmt.close();					
					if(rs != null)
						rs.close();
					rs = null;	
					pstmt = null;					
					conn.close();
					conn = null;
				}
			}
			catch(Exception d)
			{
				d.printStackTrace();
			}			
		}
		return valueXmlString.toString();
	}

	
	
	private String errorType(Connection conn , String errorCode)
	{
		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();
			while(rs.next())
			{
				msgType = rs.getString("MSG_TYPE");
			}			
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}		
		finally
		{
			try
			{
				if(rs != null)
				{
					rs.close();
					rs = null;
				}
				if(pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}		
		return msgType;
	}
	
	
	private String checkNull(String str)
	{
		if(str == null)
		{
			return "";
		}
		else
		{
			return str ;
		}

	}
}
