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 // added for ejb3
public class SiteTaxAuthority extends ValidatorEJB implements SiteTaxAuthorityLocal,SiteTaxAuthorityRemote
{
		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("hello wfvalData");
			String errString = null;
			Document dom = null;
			Document dom1 = null;
			Document dom2 = null;
			try
			{
				dom = parseString(xmlString);
				dom1 = parseString(xmlString1);
				dom2 = parseString(xmlString2);
				System.out.println("@@@@@@@@  wfValData called");
				errString = wfValData(dom,dom1,dom2,objContext,editFlag,xtraParams);
				
			}
			catch(Exception e)
			{
				throw new ITMException(e);
			}
			System.out.println("end wfvalData");
			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 = "";
			Connection conn = null;
			PreparedStatement pstmt = null ;
			ResultSet rs = null;
			String sql = "",sql1 = "",sql2 = "";
			int cnt=0;
			int currentFormNo=0;
			int childNodeListLength;
			ConnDriver connDriver = new ConnDriver();
			ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
			
			String siteCode="",sitecodePay="",taxClass="",taxEnv = "",crTerm="",userId="",currCode="",tauthCode="",
				    finSiteCode = "",finSiteCodePay = "";
			
			try
			{
				System.out.println("@@@@@@@@ wfvaldata called");
				conn = connDriver.getConnectDB("DriverITM");
				connDriver = null;
				userId = getValueFromXTRA_PARAMS(xtraParams,"loginCode");
				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"))
						{

							System.out.println("validation site_code executed");
							siteCode = genericUtility.getColumnValue("site_code",dom);
							if(siteCode != null && siteCode.trim().length() > 0)
							{
								sql =" select count(*) from site where site_code = ?  ";
								pstmt = conn.prepareStatement(sql);
								pstmt.setString(1,siteCode.trim());
								rs = pstmt.executeQuery();
								System.out.println("@@@@@@@@@  executed sql"+sql);
								if(rs.next())
								{
									cnt =  rs.getInt(1);
									if(cnt == 0) 
										 {
											errString = itmDBAccessEJB.getErrorString("","VTSITECD1",userId);
											return errString;
										 }						
								}
								if( rs != null )
								{
									rs.close();
									rs = null;
								}
								if( pstmt != null )
								{
									pstmt.close();
									pstmt = null;
								}

	   						}

							else
							{
								errString = itmDBAccessEJB.getErrorString("","VMSITECD1",userId);
								return errString;
							}
						}
						
						if(childNodeName.equalsIgnoreCase("curr_code"))
						{
							System.out.println("validation curr_code executed");
							currCode = genericUtility.getColumnValue("curr_code",dom);
						
							
							if(currCode != null && currCode.trim().length() > 0)
							{
								sql =" select count(*) from currency where curr_code = ? ";
								pstmt = conn.prepareStatement(sql);
								
								pstmt.setString(1,currCode.trim());
								rs = pstmt.executeQuery();
								System.out.println("@@@@@@@@@  executed sql"+sql);
								if(rs.next())
								{
									cnt =  rs.getInt(1);
									if(cnt == 0) 
									{
										//currency code pay entered is not defined in master.
										errString = itmDBAccessEJB.getErrorString("","VTCURRCD1 ",userId);
										return errString;
									}									
								}
								if( rs != null )
								{
									rs.close();
									rs = null;
								}
								if( pstmt != null )
								{
									pstmt.close();
									pstmt = null;
								}
	   						}

						}
					
						if(childNodeName.equalsIgnoreCase("site_code__pay"))
						{
							System.out.println("validation site_code__pay executed");
							sitecodePay = genericUtility.getColumnValue("site_code__pay",dom);
							siteCode = genericUtility.getColumnValue("site_code",dom);
							
							if(sitecodePay != null && sitecodePay.trim().length() > 0)
							{
								sql =" select count(*) from site where site_code=? ";
								pstmt = conn.prepareStatement(sql);
								
								pstmt.setString(1,sitecodePay.trim());
								rs = pstmt.executeQuery();
								System.out.println("@@@@@@@@@  executed sql"+sql);
								if(rs.next())
								{
									cnt =  rs.getInt(1);
									if(cnt == 0) 
									{
										//site code pay entered is not defined in master.
										errString = itmDBAccessEJB.getErrorString("","VTSITECP1 ",userId);
										return errString;
										
									}									
								}
								
								if(siteCode != null && siteCode.trim().length()>0)
								{
									    System.out.println("fin_entity_validate");
										PreparedStatement pstmt1 = null;
										PreparedStatement pstmt2 = null;
										ResultSet rs1 = null;
										ResultSet rs2 = null;
										
										sql1 =  "select fin_entity from site where site_code=?";
										pstmt1  = conn.prepareStatement(sql1);
										pstmt1.setString(1,sitecodePay.trim());
										rs1 = pstmt1.executeQuery();
										if(rs1.next())
										{
											finSiteCodePay = rs1.getString("fin_entity");
										}
										sql2 =  "select fin_entity from site where site_code=?";
										pstmt2  =conn.prepareStatement(sql2);
										pstmt2.setString(1,siteCode.trim());
										rs2  = pstmt2.executeQuery();
										if(rs2.next())
										{
											finSiteCode  = rs2.getString("fin_entity");
										}
										System.out.println(finSiteCode.length());
										System.out.println(finSiteCodePay.length());
										if(!(finSiteCodePay.trim().equals(finSiteCode.trim())))
										{
											System.out.println("fin_entity_compare"+finSiteCode);
											System.out.println("fin_entity_compare"+finSiteCodePay);
											errString = itmDBAccessEJB.getErrorString("","VMSITEFN1 ",userId);
											return errString;
										}
										
										if( pstmt1 != null )
										{
											pstmt1.close();
											pstmt1 = null;
										}
										if( pstmt2 != null )
										{
											pstmt2.close();
											pstmt2 = null;
										}
										if( rs1 != null )
										{
											rs1.close();
										rs = null;
										}
										if( rs2 != null )
										{
											rs2.close();
										rs = null;
										}
								}
								if( rs != null )
								{
									rs.close();
								rs = null;
								}
								
								
	   						}

						}
						
						if(childNodeName.equalsIgnoreCase("tax_class"))
						{
							System.out.println("validation tax_class executed");
							taxClass = genericUtility.getColumnValue("tax_class",dom);
						
							
							if(taxClass != null && taxClass.trim().length() > 0)
							{
								sql =" select count(*) from taxclass where tax_class=? ";
								pstmt = conn.prepareStatement(sql);
								
								pstmt.setString(1,taxClass.trim());
								rs = pstmt.executeQuery();
								System.out.println("@@@@@@@@@  executed sql"+sql);
								if(rs.next())
								{
									cnt =  rs.getInt(1);
									if(cnt == 0) 
									{
										// tax class entered is not defined in master.
										errString = itmDBAccessEJB.getErrorString("","VTTAXCLA1",userId);
										return errString;
									}									
								}
								if( rs != null )
								{
									rs.close();
									rs = null;
								}
								if( pstmt != null )
								{
									pstmt.close();
									pstmt = null;
								}
	   						}

						}
						
						if(childNodeName.equalsIgnoreCase("tax_env"))
						{
							System.out.println("validation tax_env executed");
							taxEnv = genericUtility.getColumnValue("tax_env",dom);
						
							
							if(taxEnv != null && taxEnv.trim().length() > 0)
							{
								sql =" select count(*) from taxenv where tax_env=? ";
								pstmt = conn.prepareStatement(sql);
								
								pstmt.setString(1,taxEnv.trim());
								rs = pstmt.executeQuery();
								System.out.println("@@@@@@@@@  executed sql"+sql);
								if(rs.next())
								{
									cnt =  rs.getInt(1);
									if(cnt == 0) 
									{
										// tax env entered is not defined in master.
										errString = itmDBAccessEJB.getErrorString("","VTTAXENV1",userId);
										return errString;
									}									
								}
								if( rs != null )
								{
									rs.close();
									rs = null;
								}
								if( pstmt != null )
								{
									pstmt.close();
									pstmt = null;
								}
	   						}
					
						}
						if(childNodeName.equalsIgnoreCase("tauth_code"))
						{
							System.out.println("validation tauth_code executed");
							tauthCode = genericUtility.getColumnValue("tauth_code",dom);
						
							if(tauthCode != null && tauthCode.trim().length() > 0)
							{
								sql =" select count(*) from tax_authority where tauth_code=? ";
								pstmt = conn.prepareStatement(sql);
								
								pstmt.setString(1,tauthCode.trim());
								rs = pstmt.executeQuery();
								System.out.println("@@@@@@@@@  executed sql"+sql);
								if(rs.next())
								{
										cnt =  rs.getInt(1);
									if(cnt == 0) 
									{
										// tauth code not found.
										errString = itmDBAccessEJB.getErrorString("","VTTAUTCD1",userId);
										return errString;
									}									
								}
								if( rs != null )
								{
									rs.close();
									rs = null;
								}
								if( pstmt != null )
								{
										pstmt.close();
									pstmt = null;
								}

	   							}
	
							else
							{
									//tauth code cannot be empty
								errString = itmDBAccessEJB.getErrorString("","VMTAUTCD1",userId);
								return errString;
							}
					
							
							}

						if(childNodeName.equalsIgnoreCase("cr_term"))
						{
							System.out.println("validation cr_term executed");
							crTerm = genericUtility.getColumnValue("cr_term",dom);
							
							
							if(crTerm != null && crTerm.trim().length() > 0)
							{
								sql =" select count(*) from crterm where cr_term=? ";
								pstmt = conn.prepareStatement(sql);
								
								pstmt.setString(1,crTerm.trim());
								rs = pstmt.executeQuery();
								System.out.println("@@@@@@@@@  executed sql"+sql);
								if(rs.next())
								{
									cnt =  rs.getInt(1);
									if(cnt == 0) 
									{
										// crdit term entered is not defined in master.
											errString = itmDBAccessEJB.getErrorString("","VTCRTERM1",userId);
										return errString;
									}									
								}
								if( rs != null )
								{
									rs.close();
									rs = null;
								}
								if( pstmt != null )
								{
									pstmt.close();
									pstmt = null;
								}

	   						}

							else
							{
								//credit term cannot be empty
								errString = itmDBAccessEJB.getErrorString("","VECRT2",userId);
								return errString;
							}

						}

						
						
					} // end for
										
				} //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;
		}//END OF VALIDATIONreturn errString;
	

		public String itemChanged(String xmlString,String xmlString1,String xmlString2, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException,ITMException
		{
			System.out.println("@@@@@@@ default 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 : [TrainingEJB][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="",siteDescr="", tauthCode = "",tauthName ="",tauthType="",
					chgTerm="",crTerm = "",crtermDescr ="",chgUser="";

			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("**********ITEMCHANGE FOR CASE"+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("--------------------ITM_DEFAULT-----------------------");
						Calendar currentDate = Calendar.getInstance();
						SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getApplDateFormat());
						String sysDate = sdf.format(currentDate.getTime());
						System.out.println("Now the date is :=>  " + sysDate);
								
						valueXmlString.append("<chg_date><![CDATA[").append(sysDate).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.trim());
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							siteDescr = rs.getString("descr");
						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;
						
						valueXmlString.append("<descr_1>").append("<![CDATA[" + siteDescr + "]]>").append("</descr_1>");
						
						}
						else
						{
							valueXmlString.append("<descr_1>").append("<![CDATA[]]>").append("</descr_1>");
						}
						}
					if((currentColumn.trim().equalsIgnoreCase("tauth_code")))
					{
						tauthCode = genericUtility.getColumnValue("tauth_code",dom);
						System.out.println("tauth_code ==== "+tauthCode);
						if(tauthCode != null && tauthCode.trim().length()>0 )
						{
						sql = "select tauth_type,tauth_name from tax_authority where tauth_code = ?";
						
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1,tauthCode.trim());
						rs = pstmt.executeQuery();
						while(rs.next())
						{
							tauthType = rs.getString("tauth_type");
							tauthName = rs.getString("tauth_name");
						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;
						valueXmlString.append("<tauth_name>").append("<![CDATA[" + tauthName + "]]>").append("</tauth_name>");
						valueXmlString.append("<tauth_type>").append("<![CDATA[" + tauthType + "]]>").append("</tauth_type>");
					
						}						
						else
						{
							valueXmlString.append("<tauth_name>").append("<![CDATA[]]>").append("</tauth_name>");
							valueXmlString.append("<tauth_type>").append("<![CDATA[]]>").append("</tauth_type>");	
						}
						}
						
					if((currentColumn.trim().equalsIgnoreCase("cr_term")))
					{
						crTerm = genericUtility.getColumnValue("cr_term",dom);
						System.out.println("cr_term ==== "+crTerm);
						if(crTerm != null && crTerm.trim().length()>0 )
						{
						sql = "select descr from crterm where cr_term = ?  ";
						
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1,crTerm.trim());
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							crtermDescr = rs.getString("descr");
						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;
						
						valueXmlString.append("<crterm_descr>").append("<![CDATA[" + crtermDescr + "]]>").append("</crterm_descr>");
						}
						else
						{
							valueXmlString.append("<crterm_descr>").append("<![CDATA[]]>").append("</crterm_descr>");

						}
						}
					
//					
				
					
					valueXmlString.append("</Detail1>");
				
										
				}
				valueXmlString.append("</Root>");
				
			}// end try
			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();
		}//End of itemChanged	 

	}