package ibase.webitm.ejb.adm;

import java.rmi.RemoteException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import ibase.system.config.ConnDriver;
import ibase.webitm.ejb.ValidatorEJB;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;
import javax.ejb.Stateless;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
@Stateless
public class SunGeoBiAccess extends ValidatorEJB implements	SunGeoBiAccessLocal, SunGeoBiAccessRemote 
	{
	GenericUtility genericUtility = GenericUtility.getInstance();
	String errString = "";

	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 
	{
		System.out.println("Came Inside 1 wfValdata:::");
		Document dom = null;
		Document dom1 = null;
		Document dom2 = null;
		String errFields = null;
		GenericUtility genericUtility = GenericUtility.getInstance();
		try
		{
			System.out.println("xmlString [" + xmlString + "]");
			System.out.println("xmlString1 [" + xmlString1 + "]");
			System.out.println("xmlString2 [" + xmlString2 + "]");
			if (xmlString != null && xmlString.trim().length() != 0) 
			{
				dom = genericUtility.parseString(xmlString);
			}
			if (xmlString1 != null && xmlString1.trim().length() != 0) 
			{
				dom1 = genericUtility.parseString(xmlString1);
			}
			if (xmlString2 != null && xmlString2.trim().length() != 0)
			{
				dom2 = genericUtility.parseString(xmlString2);
			}
			errFields = wfValData(dom, dom1, dom2, objContext,editFlag, xtraParams);
			System.out.println("errFields :" + errFields);
		} 
		catch (Exception e) 
		{
			System.out.println("Exception :SunGeoBiAccess :" + e.getMessage()+ ":");
			errFields = genericUtility.createErrorString(e);
		}
		System.out.println("returning from SunGeoBiAccess ");
		return errFields;
	}

	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;
		String childNodeName = "";
		int childNodeListLength = 0;
		String userId = "";
		String geoLoc = "";
		int errListSize;
		StringBuffer errStringXml = new StringBuffer("<?xml version=\"1.0\"?>\r\n<Root><Errors>");
		String errCode="";
		String errFldName="";
		//ringBuffer XmlString = new StringBuffer();
		ConnDriver connDriver = new ConnDriver();
		String msgType = "";
		Connection wfvConn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		ArrayList<String> errList = new ArrayList<String>();
		ArrayList<String> errFields = new ArrayList<String>();
		try 
		{
			System.out.println("Came inside @nd wfValdata::::");
			wfvConn = connDriver.getConnectDB("Driver");
			wfvConn.setAutoCommit(false);
			int currentFormNo = 0;
			connDriver = new ConnDriver();
			wfvConn = connDriver.getConnectDB("Driver");
			wfvConn.setAutoCommit(false);
			if (objContext != null && objContext.trim().length() > 0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}
			System.out.println("current form number::::::::::["+currentFormNo+"]");
			switch ( currentFormNo )
			{					
			case 1:
			{
			parentNodeList = dom.getElementsByTagName("Detail1");
			parentNode = parentNodeList.item(0);
			childNodeList = parentNode.getChildNodes();
			childNodeListLength = childNodeList.getLength();
			for (int ctr = 0; ctr < childNodeListLength; ctr++)
				{
				childNode = childNodeList.item(ctr);
				System.out.println("childNode"+childNode);
				if( childNode.getNodeType() != Node.ELEMENT_NODE )
				{
					continue;
				}
				childNodeName = childNode.getNodeName();
				if (childNodeName.equalsIgnoreCase("user_id"))
					{
					System.out.println("Childnode name:["+childNodeName+"]");
					userId = checkNull(genericUtility.getColumnValue("user_id", dom2));
					System.out.println("User ID got in the validation ..::["+ userId + "]");
					if (userId == null || userId.length() == 0) 
					{
						System.out.println("Invalid sitecode ::::");
						errList.add("VMGEOURID1");
						errFields.add(childNodeName.toLowerCase());
						msgType = errorType(wfvConn, "VMGEOURID1");
						if (msgType.equalsIgnoreCase("E")) 
						{
							break;
						}
					} 
					
					else 
					{
					int idCount = 0;
					String userwfsql = " SELECT COUNT (*)  AS ID_CNT FROM USERS A ,EMPLOYEE B WHERE A.CODE=? AND A.EMP_CODE=B.EMP_CODE AND B.RELIEVE_DATE IS NULL";
					pstmt = wfvConn.prepareStatement(userwfsql);
					pstmt.setString(1, userId);
					rs = pstmt.executeQuery();
					if (rs.next()) 
					{
						idCount = rs.getInt("ID_CNT");
					}
					System.out.println("IDCnt:::: " + idCount);
					if (rs != null)
					{
						rs.close();
						rs = null;
					}
					if (pstmt != null)
					{
						pstmt.close();
						pstmt = null;
					}
					if (idCount == 0)
					{
						System.out.println("Invalid sitecode , Enter valid Input::::");
						errList.add("VMGEOURID2");
						errFields.add(childNodeName.toLowerCase());
						msgType = errorType(wfvConn, "VMGEOURID2");
						System.out.println("In user id duplication validation");
						if (msgType.equalsIgnoreCase("E"))
						{
							break;
						}
					}		
				}
			}
			if (childNodeName.equalsIgnoreCase("geo_loc"))
			{
			System.out.println("Childnode name:["+childNodeName+"]");
			geoLoc = checkNull(genericUtility.getColumnValue("geo_loc", dom2));
			System.out.println("get loc value:::::::["+geoLoc+"]");
				if (geoLoc == null || geoLoc.length() == 0) 
				{
					System.out.println("Empty geo location");
					errList.add("VMGEOLCID1");
					errFields.add(childNodeName.toLowerCase());
					msgType = errorType(wfvConn, "VMGEOLCID1");						
					if (msgType.equalsIgnoreCase("E")) 
					{
						break;
					}
				}					
			else
			{
				int geoCnt = 0;
				String geoLocSql = "SELECT COUNT(*) AS GEO_CNT FROM SITE WHERE GEO_LOC=?";
				pstmt = wfvConn.prepareStatement(geoLocSql);
				pstmt.setString(1,geoLoc);
				rs = pstmt.executeQuery();
				if (rs.next()) 
				{
					geoCnt = rs.getInt("GEO_CNT");
				}
				if (rs != null)
				{
					rs.close();
					rs = null;
				}
				if (pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
				if (geoCnt == 0) 
				{
					System.out.println("Invalid Geo location code");
					errList.add("VMGEOLCID2");
					errFields.add(childNodeName.toLowerCase());
					msgType = errorType(wfvConn, "VMGEOLCID2"); 					
					if (msgType.equalsIgnoreCase("E"));
					{
						break;
					}
				}

				int dupIdCount = 0;
				String dupIdSql = " SELECT COUNT(*) AS PRIME_CNT FROM SUN_GEOBI_ACCESS WHERE USER_ID  = ? AND GEO_LOC=?";
				pstmt = wfvConn.prepareStatement(dupIdSql);
				pstmt.setString(1, userId);
				pstmt.setString(2, geoLoc);
				rs = pstmt.executeQuery();
				if (rs.next())
				{
					dupIdCount = rs.getInt("PRIME_CNT");
				}
				System.out.println("count:::: " + dupIdCount);
				if (rs != null)
				{
					rs.close();
					rs = null;
				}
				if (pstmt != null) 
				{
					pstmt.close();
					pstmt = null;
				}
				
				if (dupIdCount > 0)
				{
					System.out.println("Invalid combination,enter duplicate site code::::");
					errList.add("VMGEOLOCID");
					errFields.add(childNodeName.toLowerCase());
					msgType = errorType(wfvConn, "VMGEOLOCID");
					if (msgType.equalsIgnoreCase("E"))
					{
						break;
					}
				}
			}
		   }					
		 }
		}
	break;
	}
			errListSize = errList.size();
			System.out.println("errListSize:::::::["+errListSize+"]");
			if ( errList != null && errListSize > 0 )
			{
				System.out.println("in error::::::::::");
				for (int cnt = 0; cnt < errListSize; cnt++ )
				{
					System.out.println("in error For:::::::::::::::"); 
					errCode = (String)errList.get(cnt);
					errFldName = (String)errFields.get(cnt);
					System.out.println("errCode .........."+errCode);					
					errString = getErrorString( errFldName, errCode, userId );
					System.out.println("errString is : ::::>>>> " + errString);
					msgType =  errorType( wfvConn , 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);
						System.out.println("errStringXml .........."+errStringXml);
						errString = "";
					}
					if ( msgType.equalsIgnoreCase("E"))
					{
						break;
					}
				}
				errList.clear();
				errList = null;
				errFields.clear();
				errFields = null;				
				errStringXml.append("</Errors></Root>\r\n");
			}
			else
			{
				errStringXml = new StringBuffer( "" );
			}
			errString = errStringXml.toString();
			}
			
		catch (Exception ex) 
		{
			System.out.println("1st catch Exception::" + ex.getMessage());
			ex.printStackTrace();
			throw new ITMException(ex);
		} 
		finally 
		{
			try 
			{
				if (rs != null)
				{
					rs.close();
					rs = null;
				}
				if (pstmt != null) 
				{
					pstmt.close();
					pstmt = null;
				}
				if (wfvConn != null) 
				{
					wfvConn.close();
					wfvConn = null;
				}
			}
			catch (Exception e) 
			{
				System.out.println("Exception:::::: ::" + e.getMessage());
				throw new ITMException(e);
			}
		}
		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("Came Inside 1 itemChanged:::");
		Document dom = null;
		Document dom1 = null;
		Document dom2 = null;
		String errFields = null;
		GenericUtility genericUtility = GenericUtility.getInstance();
		try 
		{
			System.out.println("xmlString [" + xmlString + "]");
			System.out.println("xmlString1 [" + xmlString1 + "]");
			System.out.println("xmlString2 [" + xmlString2 + "]");
			if (xmlString != null && xmlString.trim().length() != 0) 
			{
				dom = genericUtility.parseString(xmlString);
			}
			if (xmlString1 != null && xmlString1.trim().length() != 0)
			{
				dom1 = genericUtility.parseString(xmlString1);
			}
			if (xmlString2 != null && xmlString2.trim().length() != 0) 
			{
				dom2 = genericUtility.parseString(xmlString2);
			}
			errFields = itemChanged(dom, dom1, dom2, objContext, currentColumn,editFlag, xtraParams);
			System.out.println("errFields :" + errFields);
		} 
		catch (Exception e) 
		{
			System.out.println("Exception :SunGeoBiAccess :" + e.getMessage()+ ":");
			errFields = genericUtility.createErrorString(e);
		}
		System.out.println("returning from SunGeoBiAccess ");
		return errFields;
	}

	public String itemChanged(Document dom, Document dom1, Document dom2,String objContext, String currentColumn, String editFlag,String xtraParams) throws RemoteException, ITMException
	{
		String userId = "";
		String userdescr = "";
		String geoLoc = "";
		StringBuffer XmlString = new StringBuffer();
		ConnDriver connDriver = new ConnDriver();
		Connection itcConn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try 
		{
			String chgUser = checkNull(genericUtility.getValueFromXTRA_PARAMS(xtraParams, "userId"));
			String chgTerm = getValueFromXTRA_PARAMS(xtraParams, "termId");
			java.util.Date currDate = new java.util.Date();
			SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getApplDateFormat());
			String chgDate = sdf.format(currDate);
			itcConn = connDriver.getConnectDB("Driver");
			itcConn.setAutoCommit(false);
			int currentFormNo = 0;
			if (objContext != null && objContext.trim().length() > 0) 
			{
				currentFormNo = Integer.parseInt(objContext);
			}
			XmlString = new StringBuffer("<?xml version=\"1.0\"?><Root><header><editFlag>");
			XmlString.append(editFlag).append("</editFlag></header>");
			System.out.println("In Detail1");
			System.out.println("Current Form No [" + currentFormNo + "]");
			System.out.println("Current column is[" + currentColumn + "]");
			System.out.println("xtraparam is [" + xtraParams + "]");
			String objNameDefault = "";
			switch ( currentFormNo )
			{					
				case 1:
				{
				XmlString.append("<Detail1 domID='1' dbID='' objContext='1' objName='"+ objNameDefault + "' selected='Y'>\r\n");
				XmlString.append("<attribute selected='N' updateFlag='A' status='N' pkNames=''/>\r\n");
				if (currentColumn.trim().equalsIgnoreCase("itm_default"))
				{
					System.out.println("value of chgDate" + chgDate);
					System.out.println("value of chgUser" + chgUser);
					System.out.println("value of chgterm" + chgTerm);
					XmlString.append("<chg_date><![CDATA[").append(checkNull(chgDate)).append("]]></chg_date>\r\n");
					XmlString.append("<chg_user><![CDATA[").append(checkNull(chgUser)).append("]]></chg_user>\r\n");
					XmlString.append("<chg_term><![CDATA[").append(checkNull(chgTerm)).append("]]></chg_term>\r\n");
				}
				if (currentColumn.trim().equalsIgnoreCase("user_id")) 
				{
					userId = checkNull(genericUtility.getColumnValue("user_id",dom2));
					System.out.println("Value of User ID [" + userId + "]");
					if (userId.length() > 0) 
					{
						String userIdSql = "select name from users where code=?";
						pstmt = itcConn.prepareStatement(userIdSql);
						pstmt.setString( 1, userId );
						rs = pstmt.executeQuery();
						if (rs.next()) 
						{
							userdescr = checkNull(rs.getString("NAME"));
						}
						System.out.println("sitedesc ..:: [" + userdescr + "]");
						if (rs != null) 
						{
							rs.close();
							rs = null;
						}
						if (pstmt != null) 
						{
							pstmt.close();
							pstmt = null;
						}
						if (userdescr.length() > 0)
						{
							XmlString.append("<username><![CDATA[").append(checkNull(userdescr)).append("]]></username>\r\n");
							
						}
					}
				}
				if (currentColumn.trim().equalsIgnoreCase("geo_loc")) 
				{
					geoLoc = checkNull(genericUtility.getColumnValue("geo_loc",dom2));
					System.out.println("value of geo location is : [" + geoLoc+ "]");
				}
				XmlString.append("</Detail1>\r\n");
			  }
				break;
			}
			
		} catch (Exception ex) 
		{
			System.out.println("1st catch Exception::" + ex.getMessage());
			ex.printStackTrace();
		} finally {
			try {
				if (rs != null) 
				{
					rs.close();
					rs = null;
				}
				if (pstmt != null) 
				{
					pstmt.close();
					pstmt = null;
				}
				if (itcConn != null) 
				{
					itcConn.close();
					itcConn = null;
				}
			} catch (Exception e) {
				System.out.println("Exception:::::: ::" + e);
				e.printStackTrace();
			}
		}
		System.out.println("value of xmlString::::" + XmlString);
		XmlString.append("</Root>\r\n");
		System.out.println("XmlString....[" + XmlString.toString());
		return XmlString.toString();
	}

private String checkNull(String input) 
{
	if (input == null)
	{
		input = "";
	} else 
	{
		input = input.trim();
	}
	return input;
}

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

}
