
/********************************************************
	Title : ProofOfExpr
	Date  : 17/10/08
	Author: pankaj singh

********************************************************/

package ibase.webitm.ejb.eou;

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.util.GregorianCalendar;
import javax.ejb.CreateException;
import javax.ejb.SessionBean;
import java.text.SimpleDateFormat;
import java.sql.Timestamp;
import java.util.StringTokenizer;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.ejb.Stateless; // added for ejb3

@Stateless

//public class ProofOfExpEJB extends ValidatorEJB implements SessionBean
public class ProofOfExp extends ValidatorEJB implements ProofOfExpLocal,ProofOfExpRemote
{

	/*
	public void ejbCreate() throws RemoteException, CreateException
	{
		System.out.println("<======= ProofOfExpr DISPLAY IS IN PROCESS ! \n Welcome!========>");
	}
	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 wfValData(String xmlString, String xmlString1,String xmlString2, String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		String errString = null;
		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)
		{
			System.out.println("Exception : ItemEJB : 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
	{
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		int ctr=0;
		String childNodeName = null;
		String errString = "";
		String errCode = "",errcode = "";
		Connection conn = null;
		PreparedStatement pstmt = null ;
		ResultSet rs = null , rs1 = null;
		String sql = "" ,sql1 = "";
		String userId = "";
		String effFromStr = null;
		String validUptoStr = null;
		String divHead="";
		double minAmount = 0;
		double maxAmount = 0;
		int cnt = 0,cnt1 = 0;
		int currentFormNo=0;
		int childNodeListLength;
        ConnDriver connDriver = new ConnDriver();
		String siteCode = "";
		try
		{
			conn = connDriver.getConnectDB("DriverITM");
			connDriver = null;
			userId = getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			GenericUtility genericUtility = GenericUtility.getInstance();
			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("site_code"))
						{
							siteCode = getColumnValue("site_code",dom);
							sql = "select count(*)  from site where site_code ='" + siteCode + "'";
							pstmt = conn.prepareStatement(sql);
							rs = pstmt.executeQuery();
							if(rs.next())
							{
								cnt = rs.getInt(1);
							}
							pstmt.close();
							rs.close();
							pstmt = null;
							rs = null;
							if (cnt == 0) 
							{	   
								errCode = "VMSITE1";
								errString = getErrorString("site_code",errCode,userId);
								 break;
							}
							
						}// End Of sc_code
						 
					}//end for	
					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();
						//  line_no__sord field is not in table
						
						 if (childNodeName.equalsIgnoreCase("ref_id"))
						{
							String refId = "",refSer = "";
							refId = genericUtility.getColumnValue("ref_id",dom);
							refSer = genericUtility.getColumnValue("ref_ser",dom);
							System.out.println("refId.."+refId);
							if(refSer.equalsIgnoreCase("D-ISS") )
							{
								sql= "select count(*) from distord_iss where tran_id = '"+ refId +"' and confirmed = 'Y'" ;
								System.out.println("sql for dist ord tran id" +sql);
								pstmt= conn.prepareStatement(sql);
								rs = pstmt.executeQuery(); 
								if(rs.next())
								{
								 cnt = rs.getInt(1);
									
								}
								pstmt.close();
								rs.close();
								pstmt = null;
								rs = null;
								System.out.println("cnt dist ord tran id" +cnt);
								if (cnt == 0)
								{
									errCode = "VTPRFTD";
									errString = getErrorString("ref_id",errCode,userId);
									break;
								}
							}
							else
							if(refSer.equalsIgnoreCase("S-DSP") )
							{
								sql= "select count(*) from despatch where desp_id = '"+ refId +"' and confirmed = 'Y'" ;
								System.out.println("sql for despatch tran id" +sql);
								pstmt= conn.prepareStatement(sql);
								rs = pstmt.executeQuery(); 
								if(rs.next())
								{
								 cnt = rs.getInt(1);
									
								}
								pstmt.close();
								rs.close();
								pstmt = null;
								rs = null;
									System.out.println("cnt despatch tran id:- " +cnt);
								if (cnt == 0)
								{
									errCode = "VTPRFTDE";
									errString = getErrorString("ref_id",errCode,userId);
									break;
								}
							}
							else
							{
								errCode = "VTPRFTS";
								errString = getErrorString("ref_id",errCode,userId);
								break;
							}
						}
					}
			} //END switch
		}//END TRY
		catch(Exception e)
		{
			System.out.println("Exception ::"+e);
			e.printStackTrace();
			errString=e.getMessage();
		}
		finally
		{
			try
			{
				if(conn!=null)
				{
					if(pstmt != null )pstmt.close();
					if(rs != null )rs.close();
					if(rs1 != null )rs.close();
					rs = null;
					rs1 = null;
					pstmt =null;
					conn.close();
				}
				conn = null;
			}catch(Exception d)
				{
				  d.printStackTrace();
				}
			System.out.println("[ProofOfExpr] Connection is Closed");
		}
		System.out.println("ErrString ::"+errString);
		return errString;
	}//END OF VALIDATION

	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);
			System.out.println("xmlString" + 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 : [ProofOfExpr][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
	{
		StringBuffer valueXmlString = new StringBuffer();
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null ;
		int ctr=0;
		String childNodeName = null;
		String columnValue = null;
		String Col_name = "";
		int currentFormNo = 0 ,cnt = 0;
		int  ShortId = 0;
		String salesPers = "" ,itemSer = "",descr = "", empCodeAprv = "";
		String fName = "",lName = "",mName = "";
		String sql = "",sql1 = "";
		String loginSite = "", siteCode = "";
		GregorianCalendar cal = new GregorianCalendar();
		ConnDriver connDriver = new ConnDriver();
		GenericUtility genericUtility = GenericUtility.getInstance();
		try
		{
			conn = connDriver.getConnectDB("DriverITM");
			connDriver=null;
			if(objContext != null && objContext.trim().length()>0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}
			System.out.println("FORM NO:::"+currentFormNo);
			System.out.println("\n Extra param........"+xtraParams);
			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("<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));	
					
					 if(currentColumn.trim().equalsIgnoreCase("itm_default"))
					{
						loginSite = getValueFromXTRA_PARAMS(xtraParams, "loginSiteCode");
						valueXmlString.append("<site_code>").append("<![CDATA["+loginSite.trim()+"]]>").append("</site_code>");
						valueXmlString.append("<tran_date>").append("<![CDATA["+getCurrdateAppFormat()+"]]>").append("</tran_date>");
						siteCode = getColumnValue("site_code",dom);
						sql = "select descr from site where site_code = '"+loginSite+"'";
						pstmt= conn.prepareStatement(sql);
						rs = pstmt.executeQuery();
						if(rs.next())
						 {
						   descr = rs.getString(1) == null ? "" : rs.getString(1);
						 }
						pstmt.close();
						rs.close();
						pstmt = null;
						rs = null;
						valueXmlString.append("<site_descr>").append("<![CDATA["+descr.trim()+"]]>").append("</site_descr>");
					}
					else if(currentColumn.trim().equalsIgnoreCase("site_code"))
					{
						siteCode = getColumnValue("site_code",dom);
						sql = "select descr from site where site_code = '"+siteCode+"'";
						System.out.println("sql for site descr:- " + sql);
						pstmt= conn.prepareStatement(sql);
						rs = pstmt.executeQuery();
						if(rs.next())
						 {
						   descr = rs.getString(1) == null ? "" : rs.getString(1);
						 }
						pstmt.close();
						rs.close();
						pstmt = null;
						rs = null;
						if(descr == null || descr.trim().length() == 0 )
						{
							valueXmlString.append("<site_descr>").append("").append("</site_descr>");
						}
						else
						{
							valueXmlString.append("<site_descr>").append("<![CDATA["+descr.trim()+"]]>").append("</site_descr>");
						}	
					}
					else if(currentColumn.trim().equalsIgnoreCase("emp_code__aprv"))
					{
						empCodeAprv = getColumnValue("emp_code__aprv",dom);
						sql = "select emp_fname,emp_mname,emp_lname from employee where emp_code = '" + empCodeAprv + "'";
						pstmt= conn.prepareStatement(sql);
						rs = pstmt.executeQuery();
						if(rs.next())
						 {
						   fName = rs.getString("emp_fname") == null ? "" : rs.getString("emp_fname");
						   mName = rs.getString("emp_mname") == null ? "" : rs.getString("emp_mname");
						   lName = rs.getString("emp_lname") == null ? "" : rs.getString("emp_lname");
						 }
						pstmt.close();
						rs.close();
						pstmt = null;
						rs = null;
						valueXmlString.append("<employee_emp_fname>").append("<![CDATA["+fName.trim()+"]]>").append("</employee_emp_fname>");
						valueXmlString.append("<employee_emp_mname>").append("<![CDATA["+mName.trim()+"]]>").append("</employee_emp_mname>");
						valueXmlString.append("<employee_emp_lname>").append("<![CDATA["+lName.trim()+"]]>").append("</employee_emp_lname>");
					}
				valueXmlString.append("</Detail1>");
				System.out.println("valueXmlString after detail 1: - " + valueXmlString);
				break;
				case 2:
				parentNodeList = dom.getElementsByTagName("Detail2");
				parentNode = parentNodeList.item(0);
				childNodeList = parentNode.getChildNodes();
				ctr = 0;
				valueXmlString.append("<Detail2>");
				childNodeListLength = childNodeList.getLength();
				do
				{
					childNode = childNodeList.item(ctr);
					childNodeName = childNode.getNodeName();
					if(childNodeName.equals(currentColumn.trim()))
					{
						if (childNode.getFirstChild() != null)
						{
							columnValue = childNode.getFirstChild().getNodeValue();
						}
					}
					ctr++;
				}
				while(ctr < childNodeListLength && !childNodeName.equals(currentColumn));
				System.out.println("currentColumn..." + currentColumn);
				/* if(currentColumn.trim().equalsIgnoreCase("itm_default"))
				{
					valueXmlString.append("<ref_ser protect =\"1\">").append("<![CDATA[D-ISS]]>").append("</ref_ser>");					
				} */
				if(currentColumn.trim().equalsIgnoreCase("ref_id"))
				{
					String  refId = "",lineNoStr = "",varValue = "",refSer = "";
					double taxAmt = 0;
					int line = 0;
					refId = genericUtility.getColumnValue("ref_id",dom);
					refSer = genericUtility.getColumnValue("ref_ser",dom);
					lineNoStr = genericUtility.getColumnValue("line_no",dom);
					line = Integer.parseInt(lineNoStr);
					System.out.println("refSer:- " + refSer);
					if(line <= 9 )
					{
						lineNoStr = "  " + lineNoStr;
						System.out.println("lineNoStr : " + lineNoStr);
					}
					else if(line > 9 && line <= 99)
					{
						lineNoStr = " " + lineNoStr;
						System.out.println("lineNoStr : " + lineNoStr);
					}
					sql = "select var_value from disparm where var_name = 'B17_BOND_TAX_CODE'";
					System.out.println("sql for site descr:- " + sql);
					pstmt= conn.prepareStatement(sql);
					rs = pstmt.executeQuery();
					if(rs.next())
					 {
					   varValue = rs.getString(1) == null ? "" : rs.getString(1);
					 }
					pstmt.close();
					rs.close();
					pstmt = null;
					rs = null;
					Object p[] = new Object[100];
					int i =0;
					StringTokenizer st = new StringTokenizer(varValue,",");
					String ret = "";
					int j = st.countTokens() - 1;
					System.out.println("j :- " + j);
					while(st.hasMoreTokens() )
					{
						p[i] = st.nextElement();
						System.out.println("p:- " + p[i]);
						if( i == j)
						{
							ret =   ret + "'" + p[i] + "'";
						}
						 else
						{
							ret =   ret + "'" + p[i] + "'" + ",";
						} 
						i++;
					}
					System.out.println("ret " + ret);
					/* if(refSer.equalsIgnoreCase("D-ISS ") )
					{
						sql = " select Sum(case when tax_amt is null then 0 else tax_amt end) "
							+ " from   taxtran Where  tran_code = 'D-ISS' "
							+ " and tran_id = '" + refId + "'"
							+ " and line_no = '" +  lineNoStr + "'"
							+ " and tax_code IN (" + ret + ")";
					}
					else if(refSer.equalsIgnoreCase("S-DSP ") )
					{
						sql = " select Sum(case when tax_amt is null then 0 else tax_amt end) "
							+ " from   taxtran Where  tran_code = 'S-DSP' "
							+ " and tran_id = '" + refId + "'"
							+ " and line_no = '" +  lineNoStr + "'"
							+ " and tax_code IN (" + ret + ")";
					} */
					sql = " select Sum(case when tax_amt is null then 0 else tax_amt end) "
							+ " from   taxtran Where  tran_code = '" + refSer + "'"
							+ " and tran_id = '" + refId + "'"
							+ " and tax_code IN (" + ret + ")";
					System.out.println("refId:- " + refId + " lineNoStr: " + lineNoStr + " refSer " +refSer);
					
					System.out.println("sql for tax_amt:........ " + sql);
					pstmt= conn.prepareStatement(sql);
					rs = pstmt.executeQuery();
					if(rs.next())
					 {
					   taxAmt = rs.getDouble(1);
					 }
					pstmt.close();
					rs.close();
					pstmt = null;
					rs = null;
					valueXmlString.append("<tax_amt protect =\"1\">").append(taxAmt).append("</tax_amt>");					
				}
				valueXmlString.append("</Detail2>");
				break;
		   	}//end of switch
			valueXmlString.append("</Root>");
			System.out.println("valueXmlString........:- " + valueXmlString);
		}//END OF TRY
		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();
			}
			System.out.println("[ProofOfExpr] CONNECTION is CLOSED");
		}
		System.out.println("valueXmlString:::::"+valueXmlString.toString());
		return valueXmlString.toString();
	 }//END OF ITEMCHANGE
	 private String getCurrdateAppFormat()
    {
        String s = "";				  
        GenericUtility genericUtility = GenericUtility.getInstance();
        try
        {
            java.util.Date date = null;
            Timestamp timestamp = new Timestamp(System.currentTimeMillis());
            System.out.println(genericUtility.getDBDateFormat());
            
            SimpleDateFormat simpledateformat = new SimpleDateFormat(genericUtility.getDBDateFormat());
            date = simpledateformat.parse(timestamp.toString());
            timestamp = Timestamp.valueOf(simpledateformat.format(date).toString() + " 00:00:00.0");
            s = (new SimpleDateFormat(genericUtility.getApplDateFormat())).format(timestamp).toString();
        }
        catch(Exception exception)
        {
            System.out.println("Exception in  getCurrdateAppFormat " + exception.getMessage());
        }
        return s;
    }
 }// END OF MAIN CLASS