package ibase.webitm.ejb.sys;

import java.rmi.RemoteException;
import java.util.*;
import java.util.Date;
import java.text.*;
import java.sql.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.ejb.*;
import ibase.webitm.utility.ITMException;
import ibase.webitm.utility.*;
import ibase.system.config.*;
import ibase.webitm.ejb.*;
import javax.ejb.Stateless; // added for ejb3

@Stateless // added for ejb3

public class SQLChange extends ValidatorEJB implements  SQLChangeLocal , SQLChangeRemote // SessionBean
{
	GenericUtility genericUtility = GenericUtility.getInstance();
	ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
	
	/*public void ejbCreate() throws RemoteException, CreateException 
	{
		System.out.println("Entering into SQLChangeEJB.............");
	}
	public void ejbRemove()
	{
	}
	public void ejbActivate() 
	{
	}
	public void ejbPassivate() 
	{
	}*/
	public String wfValData() throws RemoteException,ITMException
	{
		return "";
	}

	public String itemChanged() throws RemoteException,ITMException
	{
		return "";
	}
	

	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); //returns the DOM Object for the passed XML Stirng
			System.out.println("xmlString :" + xmlString);
			dom1 = parseString(xmlString1); //returns the DOM Object for the passed XML Stirng
			System.out.println("xmlString1 :" + xmlString1);
			
			if (xmlString2.trim().length() > 0 )
			{
				dom2 = parseString("<Root>" + xmlString2+ "</Root>");
			}
			valueXmlString = itemChanged(dom,dom1,dom2,objContext,currentColumn,editFlag,xtraParams);
		}
		catch(Exception e)
		{
			System.out.println("Exception : [SQLChangeEJB][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
	{
		
		Connection conn = null;
		Statement stmt = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		ResultSet rs1 = null;
		StringBuffer valueXmlString = new StringBuffer();
		StringBuffer retString = new StringBuffer();
		String errCode = "";
		String sql = "";
		String columnValue = "";
		String childNodeName = "";
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		int ctr = 0;
		int n = 0;
		int currentFormNo = 0;
				 
		String userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"userId");
		System.out.println("userId ::-"+userId);
		try
		{
			conn = getConnection(); 
			if(objContext != null && objContext.trim().length()>0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}
			System.out.println("[SQLChangeEJB] [itemChanged] :currentFormNo ....." +currentFormNo);
			//valueXmlString = new StringBuffer("<?xml version=\"1.0\"?><Root><header><editFlag>");
			valueXmlString = new StringBuffer("<?xml version=\"1.0\" encoding='"+genericUtility.getValueFromXTRA_PARAMS( xtraParams, "charEnc" )+"'?><Root><header><editFlag>");
			valueXmlString.append(editFlag).append("</editFlag></header>");
			valueXmlString.append("<Detail>");								
			switch (currentFormNo)
			{
				case 1:
				parentNodeList = dom.getElementsByTagName("Detail1");
				parentNode = parentNodeList.item(0);
				childNodeList = parentNode.getChildNodes();
				ctr = 0;
				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));
					
				if (currentColumn.trim().equals("itm_default"))
				{
					
					
					if(columnValue != null)
					{
						try
						{  
							String applCurrDate = getCurrdateAppFormat();
							String empCode = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginEmpCode");
							valueXmlString.append("<tran_date protect=\"1\">").append(applCurrDate).append("</tran_date>");
							valueXmlString.append("<emp_code__merge>").append(empCode).append("</emp_code__merge>");
							
							
							String empFName = "";
							String empMName = "";
							String empLName = "";
							String empDesc = "";
							if(columnValue != null)
							{
								try
								{  
									sql = "SELECT EMP_FNAME,EMP_MNAME,EMP_LNAME FROM EMPLOYEE WHERE EMP_CODE = '"+empCode.trim()+"'";
									stmt = conn.createStatement();
									rs = stmt.executeQuery(sql);
									System.out.println("SQL....."+sql);
									if (rs.next())
									{
										empFName = rs.getString(1);
										empMName = rs.getString(2);
										empLName = rs.getString(3);
									}
									empDesc = empFName+" "+empMName+" "+empLName;
									System.out.println("Employee Code ::- "+columnValue);
									System.out.println("Employee First Name ::- "+empFName);
									System.out.println("Employee Middle Name ::- "+empMName);
									System.out.println("Employee Last Name ::- "+empLName);
												
									valueXmlString.append("<employee_emp_fname_1>").append(empFName).append("</employee_emp_fname_1>");
									valueXmlString.append("<employee_emp_lname_1>").append(empLName).append("</employee_emp_lname_1>");
								}//try
								catch(Exception e)
								{
									System.out.println("Exception :[SQLChangeEJB][itemChanged::case 1::order_type] :==>\n"+e.getMessage());
									throw new ITMException(e);
								}
							}//if
							
							
							
							
						}//try
						catch(Exception e)
						{
							System.out.println("Exception :[SQLChangeEJB][itemChanged::case 1::order_type] :==>\n"+e.getMessage());
							throw new ITMException(e);
						}
					}//if
				}
				else if (currentColumn.trim().equals("itm_defaultedit"))
				{
					String custName = "";
					if(columnValue != null)
					{
						try
						{  
							sql = "SELECT CUST_NAME FROM CUSTOMER WHERE CUST_CODE = '"+columnValue.trim()+"'";
							stmt = conn.createStatement();
							rs = stmt.executeQuery(sql);
							System.out.println("SQL....."+sql);
							if (rs.next())
							{
								custName = rs.getString(1);
							}
							System.out.println("Customer Code ::- "+columnValue);
							System.out.println("Customer Name ::- "+custName);
										
							valueXmlString.append("<customer_cust_name>").append(custName).append("</customer_cust_name>");
						}//try
						catch(Exception e)
						{
							System.out.println("Exception :[SQLChangeEJB][itemChanged::case 1::order_type] :==>\n"+e.getMessage());
							throw new ITMException(e);
						}
					}//if
				}//else if
				else if (currentColumn.trim().equals("req_id"))
				{
					String custName = null;
					String custCode = null;
					String reqDate = null;
					if(columnValue != null)
					{
						try
						{  
							sql = "SELECT A.CUST_CODE, B.CUST_NAME, A.REQ_DATE FROM SER_REQUEST A, CUSTOMER B WHERE A.CUST_CODE = B.CUST_CODE AND A.REQ_ID  = '"+columnValue.trim()+"'";
							stmt = conn.createStatement();
							rs = stmt.executeQuery(sql);
							System.out.println("SQL....."+sql);
							if (rs.next())
							{
								custCode = rs.getString(1);
								custName = rs.getString(2);
								reqDate = rs.getString(3);
							}
							System.out.println("Customer Code ::- "+columnValue);
							System.out.println("Customer Name ::- "+custName);
										
							valueXmlString.append("<cust_code protect=\"1\">").append(custCode).append("</cust_code>");
							valueXmlString.append("<customer_cust_name>").append(custName).append("</customer_cust_name>");
							reqDate = genericUtility.getValidDateString(reqDate, genericUtility.getDBDateFormat(),genericUtility.getApplDateFormat());
							valueXmlString.append("<req_date protect=\"1\">").append(reqDate).append("</req_date>");
						}//try
						catch(Exception e)
						{
							System.out.println("Exception :[SQLChangeEJB][itemChanged::case 1::order_type] :==>\n"+e.getMessage());
							throw new ITMException(e);
						}
					}//if
				}//else if
				else if (currentColumn.trim().equals("cust_code"))
				{
					String custName = "";
					if(columnValue != null)
					{
						try
						{  
							sql = "SELECT CUST_NAME FROM CUSTOMER WHERE CUST_CODE = '"+columnValue.trim()+"'";
							stmt = conn.createStatement();
							rs = stmt.executeQuery(sql);
							System.out.println("SQL....."+sql);
							if (rs.next())
							{
								custName = rs.getString(1);
							}
							System.out.println("Customer Code ::- "+columnValue);
							System.out.println("Customer Name ::- "+custName);
										
							valueXmlString.append("<customer_cust_name>").append(custName).append("</customer_cust_name>");
						}//try
						catch(Exception e)
						{
							System.out.println("Exception :[SQLChangeEJB][itemChanged::case 1::order_type] :==>\n"+e.getMessage());
							throw new ITMException(e);
						}
					}//if
				}//else if
				else if (currentColumn.trim().equals("emp_code__given"))
				{
					String empFName = "";
					String empMName = "";
					String empLName = "";
					String empDesc = "";
					if(columnValue != null)
					{
						try
						{  
							sql = "SELECT EMP_FNAME,EMP_MNAME,EMP_LNAME FROM EMPLOYEE WHERE EMP_CODE = '"+columnValue.trim()+"'";
							stmt = conn.createStatement();
							rs = stmt.executeQuery(sql);
							System.out.println("SQL....."+sql);
							if (rs.next())
							{
								empFName = rs.getString(1);
								empMName = rs.getString(2);
								empLName = rs.getString(3);
							}
							empDesc = empFName+" "+empMName+" "+empLName;
							System.out.println("Employee Code ::- "+columnValue);
							System.out.println("Employee First Name ::- "+empFName);
							System.out.println("Employee Middle Name ::- "+empMName);
							System.out.println("Employee Last Name ::- "+empLName);
										
							valueXmlString.append("<employee_emp_fname>").append(empFName).append("</employee_emp_fname>");
							valueXmlString.append("<employee_emp_lname>").append(empLName).append("</employee_emp_lname>");
						}//try
						catch(Exception e)
						{
							System.out.println("Exception :[SQLChangeEJB][itemChanged::case 1::order_type] :==>\n"+e.getMessage());
							throw new ITMException(e);
						}
					}//if
				}//else if
				else if (currentColumn.trim().equals("emp_code__merge"))
				{
					String empFName = "";
					String empMName = "";
					String empLName = "";
					String empDesc = "";
					if(columnValue != null)
					{
						try
						{  
							sql = "SELECT EMP_FNAME,EMP_MNAME,EMP_LNAME FROM EMPLOYEE WHERE EMP_CODE = '"+columnValue.trim()+"'";
							stmt = conn.createStatement();
							rs = stmt.executeQuery(sql);
							System.out.println("SQL....."+sql);
							if (rs.next())
							{
								empFName = rs.getString(1);
								empMName = rs.getString(2);
								empLName = rs.getString(3);
							}
							empDesc = empFName+" "+empMName+" "+empLName;
							System.out.println("Employee Code ::- "+columnValue);
							System.out.println("Employee First Name ::- "+empFName);
							System.out.println("Employee Middle Name ::- "+empMName);
							System.out.println("Employee Last Name ::- "+empLName);
										
							valueXmlString.append("<employee_emp_fname_1>").append(empFName).append("</employee_emp_fname_1>");
							valueXmlString.append("<employee_emp_lname_1>").append(empLName).append("</employee_emp_lname_1>");
						}//try
						catch(Exception e)
						{
							System.out.println("Exception :[SQLChangeEJB][itemChanged::case 1::order_type] :==>\n"+e.getMessage());
							throw new ITMException(e);
						}
					}//if
				}//else if
				valueXmlString.append("</Detail>");	
				break;
			}//Switch		
			valueXmlString.append("</Root>");				
		}//try
		catch(Exception e)
		{
			System.out.println("Exception ::"+e.getMessage());
		}	
		finally
		{
			try
			{
				conn.close();
				conn = null;
			}
			catch(Exception s){}
		}
		return valueXmlString.toString();
	}//itemChanged()
	
	public String wfValData(String xmlString, String xmlString1,String xmlString2, String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		Document dom = null;
		Document dom1 = null;
		Document dom2 = null;
		String  errString = null;
		System.out.println("Entering into  validations ...................");
		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)
		{
			System.out.println("Exception : PayableOpeningsEJB : wfValData(String xmlString) : ==>\n"+e.getMessage());
		}
		return (errString);
	}

	public String wfValData(Document dom, Document dom1,Document dom2, String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		Connection conn = null;
		Statement stmt = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String errString = "";
		String errCode = "";
		String sql = "";
		String userId = ""; 
		String custCode = "";
		String empCodeGiven = "";
		String empCodeMerge = "";
		String childNodeName = ""; 
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		int ctr,currentFormNo=0;
		int childNodeListLength;
		try
		{
			conn = getConnection(); 
			stmt = conn.createStatement();
			userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"userId");
			System.out.println("userId = "+userId);
			System.out.println("xtraParams = "+xtraParams);
		
			if(objContext != null && objContext.trim().length()>0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}

			parentNodeList = dom.getElementsByTagName("Detail" + currentFormNo);
			parentNode = parentNodeList.item(0);
			childNodeList = parentNode.getChildNodes();
			childNodeListLength = childNodeList.getLength();
			for (ctr = 0; ctr < childNodeListLength; ctr++)
			{
				childNode = childNodeList.item(ctr);
				childNodeName = childNode.getNodeName();
				switch (currentFormNo)
				{
					case 1:
					{
						if (childNodeName.equals("cust_code"))
						{
							System.out.println("childNodeName 1. : " + childNodeName);
							custCode = genericUtility.getColumnValue("cust_code",dom);
							System.out.println("childNode.getFirstChild() 1. : " + childNode.getFirstChild());
							if (childNode.getFirstChild() == null)
							{
								errCode = "VECUST2";
								errString = getErrorString("cust_code",errCode,userId);
								break;
							}
							else if(custCode != null && custCode.trim().length()>0)
							{
								sql = "SELECT COUNT(1) AS COUNT FROM CUSTOMER WHERE CUST_CODE = '"+custCode.trim()+"'";
								rs = stmt.executeQuery(sql);
								System.out.println("SQL......"+sql);
								if (rs.next())
								{
									int cnt = rs.getInt("COUNT");
									if (cnt == 0)
									{
										errCode = "VMCUSTCDX";
										errString = getErrorString("cust_code",errCode,userId);
										break;
									}
								}
							}//else
						}//if
						if (childNodeName.equals("itm_ver"))
						{
							System.out.println("childNodeName 1. : " + childNodeName);
							custCode = genericUtility.getColumnValue("itm_ver",dom);
							System.out.println("childNode.getFirstChild() 1. : " + childNode.getFirstChild());
							if (childNode.getFirstChild() == null)
							{
								errCode = "VTITMVER";
								errString = getErrorString("itm_ver",errCode,userId);
								break;
							}
						}//if
						else if (childNodeName.equals("emp_code__given"))
						{
							System.out.println("childNodeName 1. : " + childNodeName);
							empCodeGiven = genericUtility.getColumnValue("emp_code__given",dom);
							System.out.println("childNode.getFirstChild() 1. : " + childNode.getFirstChild());
							if (empCodeGiven == null || empCodeGiven.trim().length() == 0)
							{
								errCode = "VTEMPNOEX";
								errString = getErrorString("emp_code__given",errCode,userId);
								break;
							}
							else if(empCodeGiven != null && empCodeGiven.trim().length()>0)
							{
								sql = "SELECT COUNT(1) AS COUNT FROM EMPLOYEE WHERE EMP_CODE = '"+empCodeGiven.trim()+"'";
								rs = stmt.executeQuery(sql);
								System.out.println("SQL......"+sql);
								if (rs.next())
								{
									int cnt = rs.getInt("COUNT");
									if (cnt == 0)
									{
										errCode = "VMEMPCD1";
										errString = getErrorString("emp_code__given",errCode,userId);
										break;
									}
								}
							}//else
						}//if
						else if (childNodeName.equals("emp_code__merge"))
						{
							System.out.println("childNodeName 1. : " + childNodeName);
							empCodeMerge = genericUtility.getColumnValue("emp_code__merge",dom);
							System.out.println("childNode.getFirstChild() 1. : " + childNode.getFirstChild());
							if (empCodeMerge == null || empCodeMerge.trim().length() == 0)
							{
								errCode = "VTEMPNOEX";
								errString = getErrorString("emp_code__merge",errCode,userId);
								break;
							}
							else if(empCodeMerge != null && empCodeMerge.trim().length()>0)
							{
								sql = "SELECT COUNT(1) AS COUNT FROM EMPLOYEE WHERE EMP_CODE = '"+empCodeMerge.trim()+"'";
								rs = stmt.executeQuery(sql);
								System.out.println("SQL......"+sql);
								if (rs.next())
								{
									int cnt = rs.getInt("COUNT");
									if (cnt == 0)
									{
										errCode = "VMEMPCD1";
										errString = getErrorString("emp_code__merge",errCode,userId);
										break;
									}
								}
							}//else
						}//else if
						else if(childNodeName.equals("req_id"))
						{
							if(childNode.getFirstChild() == null)
							{
								errCode = "INREQ12";
								errString = getErrorString("req_id",errCode,userId);
								break;
							}
						}
						else if(childNodeName.equals("req_date"))
						{
							System.out.println("Inside Request date ...");
							if(childNode.getFirstChild() == null)
							{
								errCode = "INREQ13";
								errString = getErrorString("req_date",errCode,userId);
								break;
							}
						}
					}//case1
					break;
				}//switch
			}//for
		}//try
		catch(Exception e)
		{
			System.out.println("Exception ::"+e);
			e.printStackTrace();
		}
		finally
		{
			try
			{
				System.out.println("Closing Connection.....");
				conn.close();
				conn = null;
			}catch(Exception se){}
		}
		System.out.println("ErrString ::"+errString);
		return errString;
	}//wfValData
	
	private String getCurrdateAppFormat()
{
	String currAppdate ="";
	java.sql.Timestamp currDate = null;
	try
	{
			Object date = null;
			currDate =new java.sql.Timestamp(System.currentTimeMillis()) ;
			System.out.println(genericUtility.getDBDateFormat());
			SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getDBDateFormat());
			date = sdf.parse(currDate.toString());
			currDate =	java.sql.Timestamp.valueOf(sdf.format(date).toString() + " 00:00:00.0");
			currAppdate = new SimpleDateFormat(genericUtility.getApplDateFormat()).format(currDate).toString();
	}
	catch(Exception e)
	{
		 
		System.out.println("Exception in :::calcFrsBal"+e.getMessage());
	}
	return (currAppdate);
}

}//class