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.SQLException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import org.w3c.dom.*;
import ibase.webitm.ejb.ValidatorEJB;
/**
*
* @author cpandey
*/
@Stateless

public class DeviceAuthentication extends ValidatorEJB implements DeviceAuthenticationRemote,DeviceAuthenticationLocal
	{
		GenericUtility genericUtility=GenericUtility.getInstance();
		public String wfValData(String xmlString, String xmlString1, String objContext, String editFlag, String xtraParams) throws ITMException
		{
			String errString="";
			Document dom=null;
			Document dom1=null;

			try {
				System.out.println("xmlString---------"+xmlString);
				System.out.println("xmlString1---------"+xmlString1);
				dom = parseString(xmlString);
				dom1=parseString(xmlString1);
				errString=wfValData(dom, dom1, objContext, editFlag, xtraParams);

			} catch (RemoteException ex)
			{
				throw new ITMException(ex);
			}
			return errString;
		}
		public String wfValData(Document dom,Document dom1,String objContext,String editFlag,String xtraParams) throws RemoteException,ITMException
		{

			NodeList parentNodeList=null;
			NodeList childNodeList=null;
			Node parentNode=null;
			Node childNode=null;
			String childNodeName=null;
			int childNodeListLength=0;
			String errString="";
			String errCode="";
			String errFieldName="";
			String errorType="";
			String userId="";
			Connection conn=null;
			ResultSet rs=null;
			String deviceId = "",dDescr = "",userIdDef = "";
			int cont = 0;
			int currentFormNo=0;
			PreparedStatement pstmt = null;
			ArrayList <String> errList=new ArrayList<String>();
			ArrayList<String> errFields = new ArrayList<String>();
			ConnDriver connDriver=new ConnDriver();
			StringBuffer errStringXml = new StringBuffer("<?xml version=\"1.0\"?>\r\n<Root><Errors>");

			try
			{
				conn=connDriver.getConnectDB("DriverITM");
				connDriver=null;
				userId=getValueFromXTRA_PARAMS(xtraParams,"loginCode");
				System.out.println("1---currentFormNo-------"+currentFormNo);
				if(objContext!=null && objContext.trim().length()>0)
				{
					currentFormNo=Integer.parseInt(objContext);
				}
				System.out.println("2----currentFormNo-------"+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);
						childNodeName=childNode.getNodeName();

						//VALIDATION FOR NULL VALUE OF DEVICE_ID AND DUPLICATE DEVICE ID
						if (childNodeName.equalsIgnoreCase("device_id"))
						{
							if(!("E".equalsIgnoreCase(editFlag)))
							{
							deviceId = getColumnValue("device_id",dom);  
							System.out.println("+++++++++ device id 1+++++++++"+deviceId);
							if ( deviceId == null || deviceId.trim().length() == 0 )
							{
								errList.add("VMDID"); 
								errFields.add("device_id");
								System.out.println("DEVICE ID COMMING NULL IN WFVALDATA & DEVICE ID++ IS : \t"+deviceId);
							}
							else 
							{
								String sql = "select count(1) from device_auth where device_id = ? ";                           
								pstmt= conn.prepareStatement(sql);
								pstmt.setString(1,deviceId);
								rs = pstmt.executeQuery();
								while(rs.next())
								{
								if(rs.getInt(1)==1)
								{
									errList.add("VMDDI");
									errFields.add("device_id");
									System.out.println("device id in device_auth table");
									break;
								}
								}                           
								pstmt.close();
								rs.close();
								rs = null;
								pstmt = null;
								
							}
							}
							}

						
						//VALIDATION FOR DESCRIPTION 
						if (childNodeName.equalsIgnoreCase("descr"))
						{
							dDescr = getColumnValue("descr",dom);  
							System.out.println("+++++++++ customer code 1+++++++++"+dDescr);
							if ( dDescr == null || dDescr.trim().length() == 0 )
							{
								errList.add("VMDEVD"); 
								errFields.add("descr");
								System.out.println("description Comming null in wfvaldata & description  is : \t"+dDescr);
							}
						}
						//VALIDATION FOR user_id__def 
						if (childNodeName.equalsIgnoreCase("user_id__def"))
						{

							userIdDef = getColumnValue("user_id__def",dom);
							if ( userIdDef == null || userIdDef.trim().length() == 0 )
							{
								errList.add("VMUIDN"); 
								errFields.add("user_id__def");
								System.out.println("USER ID DEF COMMING NULL IN WFVALDATA & USER ID DEF  >> is : \t"+userIdDef);
							}
							else
							{
							System.out.println("+++++++++ USER TABLE+++++++++"+userIdDef);
							String sql = "SELECT COUNT(1)  FROM USERS WHERE CODE = ? ";                           
							pstmt= conn.prepareStatement(sql);
							pstmt.setString(1,userIdDef);
							rs = pstmt.executeQuery();
							while(rs.next())
							{
							if(rs.getInt(1)==0)
							{
								errList.add("VMUIDD");
								errFields.add("user_id__def");
								break;
							}       
							}
							pstmt.close();
							rs.close();
							rs = null;
							pstmt = null;                           
						}
						}
										
					}

					int errListSize=errList.size();
					if(errListSize>0)
					{
						for(int cnt=0;cnt<errListSize;cnt++)
						{
							errCode=errList.get(cnt);
							errFieldName=errFields.get(cnt);
							errString=getErrorString(errFieldName, errCode, userId);
							errorType =  errorType( conn , errCode );

							if ( errString.length() > 0)
							{
								String bifurErrString = errString.substring( errString.indexOf("<Errors>") + 8,errString.indexOf("<trace>"));
								// bifurErrString = bifurErrString;
								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 OF SWITCH
			}
				
			catch(Exception e)
			{
				System.out.println(e);
				e.printStackTrace();
			}
			finally
			{

				try
				{
					if(conn!=null)
					{
						conn.close();
					}
					conn=null;
				} catch (Exception ex) {
					Logger.getLogger(DeviceAuthentication.class.getName()).log(Level.SEVERE, null, ex);
				}
			}
			errString = errStringXml.toString();
			return errString;
		}

		public String itemChanged(String xmlString, String xmlString1,String objContext,String currentColumn,String editFlag,String xtraParams)
		{
			System.out.println(" $$ xmlString ::"+xmlString);
			System.out.println(" $$ xmlString2 ::"+xmlString1);

			Document dom=null;
			Document dom1=null;
			String valueXmlString="";
			try
			{
				dom = parseString(xmlString);
				dom1 = parseString(xmlString1);
				valueXmlString=itemChanged(dom, dom1, objContext, currentColumn, editFlag, xtraParams);
			}catch(Exception e)
			{
				System.out.println(e);
			}
			return valueXmlString;
		}

		public String itemChanged(Document dom,Document dom1,String objContext,String currentColumn,String editFlag,String xtraParams)
		{
			NodeList parentNodeList=null;
			NodeList childNodeList=null;
			Node parentNode=null;
			Node childNode=null;
			String childNodeName=null;
			int childNodeListLength=0;
			ConnDriver connDriver=new ConnDriver();
			Connection conn=null;
			StringBuffer valueXmlString=null;
			PreparedStatement pstmt=null;
			ResultSet rs=null;
			String sql = "";
			String columnValue = "",useridDef = "",userName = "";
			int currentFormNo=0;
			int ctr = 0;

			try
			{
				conn = connDriver.getConnectDB("DriverITM");
				conn.setAutoCommit(false);
				connDriver=null;
				if(objContext != null && objContext.trim().length()>0)
				{
					currentFormNo = Integer.parseInt(objContext);
				}
				valueXmlString = new StringBuffer("<?xml version=\"1.0\"?><Root><header><editFlag>");
				valueXmlString.append(editFlag).append("</editFlag></header>");
				switch(currentFormNo)
				{
				case 1 :
					parentNodeList = dom.getElementsByTagName("Detail1");
					parentNode = parentNodeList.item(0);
					childNodeList = parentNode.getChildNodes();
					ctr = 0;
					valueXmlString.append("<Detail>");
					System.out.println("+++++++++++++current form no++++++++++"+currentFormNo);
					childNodeListLength = childNodeList.getLength();
					do
					{
						childNode = childNodeList.item(ctr);
						childNodeName = childNode.getNodeName();
						if(childNodeName.equals(currentColumn))
						{
							if (childNode.getFirstChild() != null)
							{
								columnValue = childNode.getFirstChild().getNodeValue().trim();
							}
							System.out.println("in do while loop "+columnValue);
						}
						ctr++;
					}while(ctr < childNodeListLength  && !childNodeName.equals(currentColumn));
					System.out.println("[" + currentColumn + "] ==> '" + columnValue + "'");
					if(currentColumn.equalsIgnoreCase("user_id__def"))
					{
						useridDef =  genericUtility.getColumnValue("user_id__def",dom) ;
						System.out.println("++++++user code from  users table++++++++++++++"+useridDef);
						sql = "SELECT NAME FROM USERS WHERE CODE = ?";
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1,useridDef);
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							userName=rs.getString("NAME")==null?"":rs.getString("NAME");
							System.out.println("users name "+userName);

						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;
						valueXmlString.append("<name>").append("<![CDATA[" +userName+ "]]>").append("</name>");
					}
					valueXmlString.append("</Detail>");
					break ;
				}
				valueXmlString.append("</Root>");
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
			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();
				}
			}
			System.out.println("VALUE STRING"+valueXmlString.toString());
			return valueXmlString.toString();
		}
		private String errorType( Connection conn , String errorCode )
		{
			String msgType = "";
			System.out.println("IN ERROR METHOD");
			PreparedStatement pstmt = null ;
			ResultSet rs = null;
			try
			{
				String  sql = " SELECT MSG_TYPE FROM MESSAGES WHERE MSG_NO =   ? ";
				System.out.println("SQL IS EXECUTING");
				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;
		}

	}



