package ibase.webitm.ejb.fin;

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.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.ejb.Stateless; // added for ejb3
import ibase.webitm.ejb.ITMDBAccessEJB;

@Stateless
public class SiteSalesPerson extends ValidatorEJB implements SiteSalesPersonLocal,SiteSalesPersonRemote
{
	GenericUtility genericUtility = GenericUtility.getInstance(); 
	public String wfValData(String xmlString, String xmlString1, String xmlString2,String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		System.out.println("------------ wfvalData method called-----------------");
		String errString = null;
		Document dom = null;
		Document dom1 = null;
		Document dom2 = null;
		try
		{
			dom = parseString(xmlString);
			dom1 = parseString(xmlString1);
			dom2 = parseString(xmlString2);
			errString = wfValData(dom,dom1,dom2,objContext,editFlag,xtraParams);
			
		}
		catch(Exception e)
		{
			System.out.println("Exception : SiteSalesPerson.java : wfValData(String xmlString) : ==>\n"+e.getMessage());
			throw new ITMException(e);
		}
		
		return errString;
	} //end of wfValData 
	
	
	@SuppressWarnings("null")
	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 = "";
		Connection conn = null;
		PreparedStatement pstmt = null ;
		ResultSet rs = null;
		String sql = "";
		int cnt=0;
		int currentFormNo=0;
		int childNodeListLength;
		ConnDriver connDriver = new ConnDriver();
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
		
		String siteCode="",salesPerson="",userId="",errCode="",siteCodePay="",crTerm="",taxENV="",taxClass="";
		
		try
		{
			conn = connDriver.getConnectDB("DriverITM");
			connDriver = null;
			userId = getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			System.out.println("user ID form XtraParam : "+userId);
			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 = genericUtility.getColumnValue("site_code",dom);							


						if (siteCode == null || siteCode.trim().length() == 0 )
						{
								errCode = "VMSITENULL";
								errString = getErrorString("site_code",errCode,userId);
								break;
						}
						else
						{
							sql = "select count(1) from site where  site_code = ? ";
							pstmt=conn.prepareStatement(sql);
							pstmt.setString(1,siteCode);
							rs = pstmt.executeQuery();
							if(rs.next())
							{
								cnt = rs.getInt(1);
							}
							pstmt.close();
							rs.close();
							pstmt = null;
							rs = null;
							if(cnt == 0)
							{
								errCode = "VMSITENVAL";
								errString = getErrorString("site_code",errCode,userId);
								break;
							}
						}
					}
					 if(childNodeName.equalsIgnoreCase("sales_pers"))
					 {
						 salesPerson=genericUtility.getColumnValue("sales_pers",dom);
						 if(salesPerson==null || salesPerson.trim().length()==0)
						 {
							 errCode = "VMSITPERNL";
							 errString = getErrorString("site_code",errCode,userId);
							break;
						 }
						 else
						 {
							 	sql = "select count(1) from sales_pers where  sales_pers = ? ";
								pstmt=conn.prepareStatement(sql);
								pstmt.setString(1,salesPerson);
								rs = pstmt.executeQuery();
								if(rs.next())
								{
									cnt = rs.getInt(1);
								}
								pstmt.close();
								rs.close();
								pstmt = null;
								rs = null;								
								if(cnt == 0)
								{
									errCode = "VMSALPERNF";
									errString = getErrorString("site_code",errCode,userId);
									break;
								}
						 }
						 
						 
					 }
					 
					 //----------------------------------------------------
					 if(childNodeName.equalsIgnoreCase("site_code__pay"))
					 {
						 siteCodePay=genericUtility.getColumnValue("site_code__pay",dom);
						 System.out.println("@@-------siteCodePay : "+siteCodePay);	
						 if (siteCodePay !=null && siteCodePay.trim().length() > 0)	
						{	
							 	sql = "select count(1) from site where  site_code = ? ";
								pstmt=conn.prepareStatement(sql);
								pstmt.setString(1,siteCodePay);
								rs = pstmt.executeQuery();
								if(rs.next())
								{
									cnt = rs.getInt(1);
								}
								pstmt.close();
								rs.close();
								pstmt = null;
								rs = null;								
								if(cnt == 0)
								{
									errCode = "VMSITCDPY";
									errString = getErrorString("site_code__pay",errCode,userId);
									break;
								}
						}
						 
					 }
					 
					 if(childNodeName.equalsIgnoreCase("cr_term"))
					 {
						 crTerm=genericUtility.getColumnValue("cr_term",dom);
						 System.out.println("@@-------crTerm : "+crTerm);
							if (crTerm !=null && crTerm.trim().length() > 0)	 
							{							
							 	sql = "select count(1) from crterm where cr_term = ? ";
								pstmt=conn.prepareStatement(sql);
								pstmt.setString(1,crTerm);
								rs = pstmt.executeQuery();
								if(rs.next())
								{
									cnt = rs.getInt(1);
								}
								pstmt.close();
								rs.close();
								pstmt = null;
								rs = null;								
								if(cnt == 0)
								{
									errCode = "VMCRTRMNF";
									errString = getErrorString("cr_term",errCode,userId);
									break;
								}
							}
						 
					 }
					 
					 
					 
					 if(childNodeName.equalsIgnoreCase("tax_class"))
					 {
						 taxClass=genericUtility.getColumnValue("tax_class",dom);
						 System.out.println("@@------taxClass : "+taxClass);
						 if (taxClass !=null && taxClass.trim().length() > 0)	
						 {
							 	sql = "select count(1) from taxclass where tax_class = ? ";
								pstmt=conn.prepareStatement(sql);
								pstmt.setString(1,taxClass);
								rs = pstmt.executeQuery();
								if(rs.next())
								{
									cnt = rs.getInt(1);
								}
								System.out.println("Count taxClass -----: "+cnt);
								pstmt.close();
								rs.close();
								pstmt = null;
								rs = null;								
								if(cnt == 0)
								{
									errCode = "VMTAXCLSNF";
									errString = getErrorString("tax_class",errCode,userId);
									break;
								}
						 }
					 }
					 if(childNodeName.equalsIgnoreCase("tax_env"))
					 {
						 taxENV=genericUtility.getColumnValue("tax_env",dom);
						 System.out.println("@@--------- taxENV : "+taxENV);
							
						 if (taxENV !=null && taxENV.trim().length() > 0)	
						 {
							 	sql = "select count(1) from taxenv where tax_env = ? ";
								pstmt=conn.prepareStatement(sql);
								pstmt.setString(1,taxENV);
								rs = pstmt.executeQuery();
								if(rs.next())
								{
									cnt = rs.getInt(1);
								}
								System.out.println("Count taxENV -----: "+cnt);
								pstmt.close();
								rs.close();
								pstmt = null;
								rs = null;								
								if(cnt == 0)
								{
									errCode = "VMTAXENVNF";
									errString = getErrorString("tax_env",errCode,userId);
									break;
								}
						 }
					 }
			
					
				 } //end for loop
											
			} //end switch
		
		} //end try
		catch(Exception e)
		{
			System.out.println("Exception ::"+e);
			e.printStackTrace();
			errString=e.getMessage();
            throw new ITMException(e);
		}
		finally
		{
			try
			{
				if(conn!=null)
				{
					if(rs != null )
					{
						rs.close();
						rs = null;
					}
					if(pstmt != null )pstmt.close();
					pstmt =null;
					conn.close();
				}
				conn = null;
			}
			catch(Exception d)
			{
			  d.printStackTrace();
			}
		}
		
		System.out.println("ErrString ::[ "+errString+" ]");
		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("------------------ itemChanged called------------------");
		Document dom = null;
		Document dom1 = null;
		Document dom2 = null;
		String valueXmlString = "";
		try
		{   
			dom = parseString(xmlString);
			dom1 = parseString(xmlString1);
			dom2 = parseString(xmlString2);
			valueXmlString = itemChanged(dom,dom1,dom2,objContext,currentColumn,editFlag,xtraParams);
		}
		catch(Exception e)
		{
			System.out.println("Exception : [SiteSalesPerson ][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
	{

		System.out.println("@@@@@@@ itemChanged called");
		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 ;
		String childNodeName = null;
		GenericUtility genericUtility = GenericUtility.getInstance();
		ConnDriver connDriver = new ConnDriver();
		String sql="";
		int currentFormNo =0;
		String columnValue="",siteCode="",salesPerson="",chgTerm="",chgUser="",siteCodePay="",siteCodeDescr="";
		String siteCodePayDescr="",salesPersonName="";
		int ctr=0;
		
		try
		{		
			conn = connDriver.getConnectDB("DriverITM");
			conn.setAutoCommit(false);
			connDriver=null;
			if(objContext != null && objContext.trim().length()>0)
			{
				currentFormNo = Integer.parseInt(objContext.trim());
			}
			valueXmlString = new StringBuffer("<?xml version=\"1.0\"?><Root><header><editFlag>");
			valueXmlString.append(editFlag).append("</editFlag></header>");
			chgTerm = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "chg_term");
			chgUser = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "chg_user");
			System.out.println("-------- currentFormNo : "+currentFormNo);
			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));
				System.out.println("[" + currentColumn + "] ==> '" + columnValue + "'");
				
			
				if( currentColumn.trim().equalsIgnoreCase( "itm_default" ) )
				{
					System.out.println("------------in itm_default---------");
					Calendar currentDate = Calendar.getInstance();
					SimpleDateFormat simpleDateFormatObj = new SimpleDateFormat(genericUtility.getApplDateFormat());
					String systemDate = simpleDateFormatObj.format(currentDate.getTime());
					System.out.println("Now the date is :=>  " + systemDate);
							
					valueXmlString.append("<chg_date><![CDATA[").append(systemDate).append("]]></chg_date>\r\n");
					valueXmlString.append("<chg_term><![CDATA[").append(chgTerm).append("]]></chg_term>");
					valueXmlString.append("<chg_user><![CDATA[").append(chgUser).append("]]></chg_user>");
					
				}
			
				
				if((currentColumn.trim().equalsIgnoreCase("site_code")))
				{
					siteCode = genericUtility.getColumnValue("site_code",dom);
					System.out.println("site_code -----   :->> "+siteCode);
					if(siteCode != null && siteCode.trim().length()>0 )
					{
						sql = "SELECT DESCR FROM SITE WHERE SITE_CODE = ? ";
						pstmt= conn.prepareStatement(sql);
						pstmt.setString(1,siteCode);
						rs = pstmt.executeQuery();
						while(rs.next())
						{
							siteCodeDescr = rs.getString(1) == null ? "" : rs.getString(1);
						}
					rs.close();
					rs = null;
					pstmt.close();
					pstmt = null;
					
					valueXmlString.append("<site_descr>").append("<![CDATA[" + siteCodeDescr + "]]>").append("</site_descr>");
					
					System.out.println("siteCodeDescr---------- >> : "+siteCodeDescr);
					
					}
					else
					{
						valueXmlString.append("<site_descr>").append("<![CDATA[]]>").append("</site_descr>");
						
					}
				}
				
				else if((currentColumn.trim().equalsIgnoreCase("sales_pers")))
				{
					salesPerson = genericUtility.getColumnValue("sales_pers",dom);
					System.out.println("salesPerson----->> : "+salesPerson);
					if(salesPerson != null && salesPerson.trim().length()>0 )
					{
						sql = "select sp_name from sales_pers where sales_pers = ? ";
						pstmt= conn.prepareStatement(sql);
						pstmt.setString(1,salesPerson);
						rs = pstmt.executeQuery();
						while(rs.next())
						{
							salesPersonName = rs.getString(1) == null ? "" : rs.getString(1);
						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;
						valueXmlString.append("<sp_name>").append("<![CDATA[" + salesPersonName + "]]>").append("</sp_name>");
						System.out.println("salesPersonName---------- >> : "+salesPersonName);
					}
					else
					{
						valueXmlString.append("<sp_name>").append("<![CDATA[]]>").append("</sp_name>");
					}
				}
				
				if((currentColumn.trim().equalsIgnoreCase("site_code__pay")))
				{
					siteCodePay = genericUtility.getColumnValue("site_code__pay",dom);
					System.out.println("site_code__pay -----   :->> "+siteCode);
					if(siteCodePay != null && siteCodePay.trim().length()>0 )
					{
						sql = "SELECT DESCR FROM SITE WHERE SITE_CODE = ? ";
						pstmt= conn.prepareStatement(sql);
						pstmt.setString(1,siteCodePay);
						rs = pstmt.executeQuery();
						while(rs.next())
						{
							siteCodePayDescr = rs.getString(1) == null ? "" : rs.getString(1);
						}
					rs.close();
					rs = null;
					pstmt.close();
					pstmt = null;
					
					valueXmlString.append("<site_descr_pay>").append("<![CDATA[" + siteCodePayDescr + "]]>").append("</site_descr_pay>");
					
					System.out.println("siteCodePayDescr---------- >> : "+siteCodePayDescr);
					
					}
					else
					{
						valueXmlString.append("<site_descr_pay>").append("<![CDATA[]]>").append("</site_descr_pay>");
						
					}
				}
					valueXmlString.append("</Detail1>");
				}// end switch
			valueXmlString.append("</Root>");
		}
		catch(Exception e)
		{
			e.printStackTrace();
			System.out.println("Exception ::"+e.getMessage());
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if(conn!=null)
				{
					if(rs != null)
					{
						rs.close();
						rs = null;
					}
					if(pstmt != null)
					{
						pstmt.close();
						pstmt = null;
					}
					conn.close();
					conn = null;
				}
			}
			catch(Exception d)
			{
			  d.printStackTrace();
			}			
		}
		
		return valueXmlString.toString();
	}
	
	
}
