
/********************************************************
	Title : LopAmd
	Date  : 06/03/09 
	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.util.Date;
import java.sql.Timestamp;

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 LopAmdEJB extends ValidatorEJB implements SessionBean
public class LopAmd extends ValidatorEJB implements LopAmdLocal,LopAmdRemote
{
	/*
	public void ejbCreate() throws RemoteException, CreateException
	{
		System.out.println("<======= LopAmdEJB 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 : LopAmdEJB : 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 = "",lopRefNo = "",confirmed = "",itemCode = "";
		SimpleDateFormat simpleDateFrormat = null;
		Date effFrom = null,validUpto = null;
		try
		{
			
			conn = connDriver.getConnectDB("DriverITM");
			connDriver = null;
			userId = getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			GenericUtility genericUtility = GenericUtility.getInstance();
			simpleDateFrormat = new SimpleDateFormat("mm/dd/yy");
			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 site_code
						if (childNodeName.equalsIgnoreCase("lop_ref_no"))
						{
							lopRefNo = getColumnValue("lop_ref_no",dom);
							sql = "select confirmed from lop_hdr where lop_ref_no = ?";
							pstmt = conn.prepareStatement(sql);
							pstmt.setString(1,lopRefNo);
							rs = pstmt.executeQuery();
							if(rs.next())
							{
								confirmed = rs.getString("confirmed");
							}
							pstmt.close();
							rs.close();
							pstmt = null;
							rs = null;
							if (confirmed == null || confirmed.trim().length() == 0 || !confirmed.equalsIgnoreCase("Y")) 
							{	   
								errCode = "VMLOCO";
								errString = getErrorString("site_code",errCode,userId);
								 break;
							}
						}// End Of site_code
						
						else if ( childNodeName.equalsIgnoreCase( "valid_to" ) )
						{
							validUptoStr = getColumnValue( "valid_to", dom );
							effFromStr = getColumnValue( "valid_from", dom );
							System.out.println(" 'VALID UPTO' FROM DOM  =========>"+validUpto);
							/* 
							{
								errCode = "VTVLEFN";
								errString = getErrorString("valid_upto",errCode,userId);
								break;
							} */
							if( effFromStr != null && effFromStr.trim().length() > 0 && validUptoStr != null && validUptoStr.trim().length() > 0 )
							{						  
								
								SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getApplDateFormat());
								java.util.Date effFrom1 = sdf.parse(effFromStr);
								java.util.Date validUpto1 = sdf.parse(validUptoStr);
								if(validUpto1.before(effFrom1))
								{	
						            System.out.println(" ====> 'VALID UPTO' DATE  MUST BE GREATER THAN 'EFF FROM' DATE <===== ");
									errCode = "VTDATE6";
									errString = getErrorString("valid_upto",errCode,userId);
						          	break;
								}	
							} // End of (startDate!=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();
						System.out.println(" validation for :-------------" + childNodeName);
						//  line_no__sord field is not in table
						 if (childNodeName.equalsIgnoreCase("line_no_lop"))
						{
							System.out.println("In Cline_no_lop");
							String lineNoLop = "";
							lineNoLop = genericUtility.getColumnValue("line_no_lop",dom);
							if(lineNoLop != null && lineNoLop.trim().length() > 0)
							{
								sql = "select count(*) from lop_det where line_no = '" + lineNoLop + "'";
								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 = "VMLALN";
									errString = getErrorString("site_code",errCode,userId);
									 break;
								}
							}
							else
							{
								itemCode = genericUtility.getColumnValue("item_code",dom);
								if(itemCode == null || itemCode.trim().length() == 0 )
								{
									errCode = "VMITEMCD1 ";
									errString = getErrorString("item_code",errCode,userId);
									 break;
								}
							}
						}
					}//end for	
			} //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("[LOpAMdEJB] 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 : [BondEJB][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 = "",currAppdate = "",frDate = "",toDate = "";
		String fName = "",lName = "",mName = "";
		String lopRefNo = "",authLoc = "",validToStr = "",validFromStr = "";
		String itemCode = "",lineNoLop = "",itemDescr = "",buySellFlag ="",itemStatus = "",tariffHead = "";
		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 :
					valueXmlString.append("<Detail1>");
					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().equalsIgnoreCase("itm_default"))
					{
						loginSite = getValueFromXTRA_PARAMS(xtraParams, "loginSiteCode");
						System.out.println("U r in itm_default");
						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("lop_ref_no"))
					{
						
						Timestamp validUptoTs = null,validFromTs = null;
						lopRefNo = getColumnValue("lop_ref_no",dom);
						sql = "select auth_loc,valid_from,valid_to "
								+ " from lop_hdr"
								+ " where lop_ref_no = '" + lopRefNo + "'";
						pstmt= conn.prepareStatement(sql);
						rs = pstmt.executeQuery();
						if(rs.next())
						 {
						    authLoc = rs.getString("auth_loc") == null ? "" : rs.getString("auth_loc");
						    validFromTs = rs.getTimestamp("valid_from");
							validUptoTs = rs.getTimestamp("valid_to");
						 }
						pstmt.close();
						rs.close();
						pstmt = null;
						rs = null;
						validFromStr = genericUtility.getValidDateString(validFromTs.toString(),genericUtility.getDBDateFormat(),genericUtility.getApplDateFormat());
						validToStr = genericUtility.getValidDateString(validUptoTs.toString(),genericUtility.getDBDateFormat(),genericUtility.getApplDateFormat());
						
						
						valueXmlString.append("<auth_loc__o>").append(authLoc).append("</auth_loc__o>");	
						valueXmlString.append("<valid_from__o>").append(validFromStr).append("</valid_from__o>");	
						valueXmlString.append("<valid_to__o>").append(validToStr).append("</valid_to__o>");	
						
					}
					// changed by pankaj on 5/03/09
					else if(currentColumn.trim().equalsIgnoreCase("site_code"))
					{
						System.out.println("calling the site_code.....");
						siteCode = getColumnValue("site_code",dom);
						if(siteCode != null || siteCode.trim().length() > 0)
						{
							sql = "Select descr from site where site_code ='" + siteCode + "'";
							System.out.println("select qry from item.." + sql);
							pstmt= conn.prepareStatement(sql);
							rs = pstmt.executeQuery(); 
							if(rs.next())
							{
							   descr = rs.getString("descr") == null ? "" : rs.getString("descr");
							}
							System.out.println("siteDescr .." + descr);
							pstmt.close();
							rs.close();
							pstmt = null;
							rs = null;
							valueXmlString.append("<site_code>").append(siteCode).append("</site_code>");
							if(descr == null || descr.trim().length() ==0 )
							{
								valueXmlString.append("<site_descr>").append("").append("</site_descr>");	
							}
							else
							{
								valueXmlString.append("<site_descr>").append(descr).append("</site_descr>");	
							}
						}
						else
						{
							valueXmlString.append("<site_descr>").append("").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>");
					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();
								System.out.println("current node >>>>>>>>>>>>>>>>>>>>>>>> " + childNodeName );
								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("line_no_lop"))
							{
								lopRefNo = genericUtility.getColumnValue("lop_ref_no",dom1);
								lineNoLop = genericUtility.getColumnValue("line_no_lop",dom);
								sql = " select item_code,item_descr,buy_sell_flag,item_status,tariff_head "
											+ " from lop_det"
											+ " where lop_ref_no = '" + lopRefNo + "'"
											+ " and line_no = '" + lineNoLop + "'";
								pstmt= conn.prepareStatement(sql);
								rs = pstmt.executeQuery();
								if(rs.next())
								 {
								   itemCode = rs.getString("item_code") == null ? "" : rs.getString("item_code");
								   itemDescr = rs.getString("item_descr") == null ? "" : rs.getString("item_descr");
								   buySellFlag = rs.getString("buy_sell_flag") == null ? "" : rs.getString("buy_sell_flag");
								   itemStatus = rs.getString("item_status") == null ? "" : rs.getString("item_status");
								   tariffHead = rs.getString("tariff_head") == null ? "" : rs.getString("tariff_head");
								 }
								pstmt.close();
								rs.close();
								pstmt = null;
								rs = null;
								valueXmlString.append("<item_code__o>").append("<![CDATA["+itemCode.trim()+"]]>").append("</item_code__o>");
								valueXmlString.append("<item_descr__o>").append("<![CDATA["+itemDescr.trim()+"]]>").append("</item_descr__o>");
								valueXmlString.append("<buy_sell_flag__o>").append("<![CDATA["+buySellFlag.trim()+"]]>").append("</buy_sell_flag__o>");
								valueXmlString.append("<item_status__o>").append("<![CDATA["+itemStatus.trim()+"]]>").append("</item_status__o>");
								valueXmlString.append("<tariff_head__o>").append("<![CDATA["+tariffHead.trim()+"]]>").append("</tariff_head__o>");
							}
							
							
							valueXmlString.append("</Detail2>");
							break;
		   	}//end of switch
			valueXmlString.append("</Root>");
		}//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("[BondEJB] 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