/*******************************************
          Developed Date                                         3/9/2009
Modified By Ashwin on 05-Aug-10 
// For Getting Processing Sites from Scheduler's ActualParameter Instead of FINPARM
********************************************/
package ibase.webitm.ejb.sys;
import java.util.*;
import java.sql.*;
import ibase.system.config.ConnDriver;
import org.apache.axis.Constants;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import javax.xml.rpc.ParameterMode;
import ibase.utility.CommonConstants;
import java.util.*;
import ibase.webitm.utility.ITMException;
import java.rmi.RemoteException;
import org.w3c.dom.*; 
import ibase.webitm.utility.GenericUtility ;
import ibase.scheduler.utility.interfaces.Schedule;
import java.util.Date;
import java.text.SimpleDateFormat;
//import org.apache.commons.logging.LogFactory;
public class FinChargeCalcPrc implements Schedule
{
			ibase.utility.GenericUtility genericUtility = new ibase.utility.GenericUtility();          
			public String schedule( HashMap map )throws RemoteException, ITMException
			{
				
								return "";
			}
			public String schedule( String scheduleParamXML )throws RemoteException, ITMException
			{
				System.out.println("\n\n::::: FinChargeCalcPrc ::::::::: ");
				System.out.println("\n\n::::: INside scheduleParamXML  [" + scheduleParamXML + "]");
				PreparedStatement pstmt = null ;
				ResultSet rs = null ; 
				Connection conn=null;          
				String sql="";
				String userInfoList = null;
				String isIntractive = null;
				String objName = null;
				String downloadLoc = null;
				String varValue  = "",varvalue2 = "",varvalue1="",drnoteDateStr = "";
				//String addlValue =null;
				//String addlValue = "";          
				Timestamp  frDate = null ,currDate=null,addlValueTm =null;//addlValue = null;
				SimpleDateFormat currAppdate = null;
				String lsFromdateStr ="",siteCode = "",retString="",despid = "",addlValueMinFin="",varValueMinFin="",addlValueStr="",frDateStr = "";
				Timestamp lsFromdateDt = null,dateValue = null,addlValue=null;
				ArrayList paramListArr = new ArrayList();
				double timdifferance = 0.00;
				StringBuffer filterString = null;
				filterString = new StringBuffer();                    
				StringTokenizer stringTokenizer = null;
				String  varName = "";
				String  chgUse = "";
				try
				{
							if( conn == null )
							{
									ConnDriver connDriver = new ConnDriver();
									conn = connDriver.getConnectDB("DriverITM");
									conn.setAutoCommit(false);                    
							}                              
							System.out.println(" scheduleParamXML  [" + scheduleParamXML + "]");
							Document userInfoDom = new ibase.utility.GenericUtility().parseString( scheduleParamXML ); 
										
							//----- Changes Start By Ashwin  31/07/10 - Begin
							NodeList parentNodeList = null,childNodeList = null;
							Node parentNode = null,childNode = null;
							String finSites = "";
							int childNodeListLength = 0;
							String childNodeName = null;

							parentNodeList = userInfoDom.getElementsByTagName("ACTUALPARAMETERS");

							parentNode = parentNodeList.item(0);
							childNodeList = parentNode.getChildNodes();
							childNodeListLength = childNodeList.getLength();
							for(int ctr = 0; ctr < childNodeListLength; ctr++)
							{
								childNode = childNodeList.item(ctr);
								childNodeName = childNode.getNodeName();
								
								if(childNodeName!=null && !"#text".equalsIgnoreCase(childNodeName))
								{
									
									if(ctr==0)
									{
										finSites=childNode.getFirstChild().getNodeValue();
									}
								}
							}
							System.out.println("\n\n :::: finSites["+finSites+"]");

							//----- Changes End By Ashwin 31/07/10  - End

						NodeList paramList = userInfoDom.getElementsByTagName( "SCHEDULE" );
						Node currDetail = null ;                              
						int noOfParam = paramList.getLength();
						//System.out.println("noOfParam>>>>>"+noOfParam);
						for( int paramCnt = 0; paramCnt < noOfParam ; paramCnt++ )
						{
								currDetail = paramList.item(paramCnt);
								siteCode = currDetail.getAttributes().getNamedItem("id").getNodeValue();
						}
						//start code 08/10/09

						chgUse = userInfoDom.getElementsByTagName( "loginCode" ).item(0).getFirstChild().getNodeValue();

						 //System.out.println("loginCodeBase>>>"+loginCodeBase);                                                  
						//end code 08/10/09

							// code to be migrate for itmdefault                    
							java.sql.Timestamp drnoteDate = new java.sql.Timestamp( System.currentTimeMillis() );
							drnoteDateStr = genericUtility.getValidDateString(drnoteDate.toString(),genericUtility.getDBDateFormat(),genericUtility.getApplDateFormat());
							//System.out.println("drnoteDate>>>"+drnoteDate);
							sql="select var_value, addl_value "
												+"           from finparm "
												+" where  var_name='FIN_CHARGE_DATE' "
												+"                     and prd_code='999999' " ;
							pstmt = conn.prepareStatement( sql );          
							rs = pstmt.executeQuery();
							if( rs.next() )         
							{          
												varValue = rs.getString("var_value")==null?"":rs.getString("var_value");
												addlValueStr = rs.getString("addl_value") ;
							}
							System.out.println(">>>>>>>>>>>>value>>>>>>>" + varValue);          
							System.out.println(">>>>>>>>>>>>addlValue>>>>>>>" + addlValueStr);          
							rs.close();
							rs=null;
							pstmt.close();
							pstmt = null;
							
							if(varValue==null || varValue.trim().length()==0)
							{
										varValue = "P";
							}
							if( "P".equalsIgnoreCase( varValue ) && addlValueStr != null )
							{
												
										// 12/09/09 manoharan first change to db date format
										//addlValueStr = genericUtility.getValidDateString(addlValue.toString(),genericUtility.getDBDateFormat(),genericUtility.getApplDateFormat());
										frDateStr = addlValueStr ; //genericUtility.getValidDateString(addlValueStr.toString(), genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat());
										// end 12/09/09 manoharan first change to db date format
										//frDate = java.sql.Timestamp.valueOf(frDateStr + " 00:00:00");          
										System.out.println("frDateStr>>>>>>>>"+frDateStr);
							}else if( "U".equalsIgnoreCase( varValue ) )
							{                                                            
										frDate =null;
							}
							else if( "F".equalsIgnoreCase( varValue ) )
							{
										sql=" select fr_date from acctprd where code = ( select acct_prd from parameter )" ;
										pstmt = conn.prepareStatement(sql);
										rs = pstmt.executeQuery();
										if( rs.next() )
										{
															frDate = rs.getTimestamp("fr_date");
										}
										//System.out.println("frDate>>>>>>>>"+frDate);
										frDateStr = genericUtility.getValidDateString(frDate.toString(),genericUtility.getDBDateFormat(), genericUtility.getApplDateFormat());
										//System.out.println("frDateStr>>>>>>>>"+frDateStr);
										rs.close();
										rs=null;
										pstmt.close();
										pstmt=null;                                        
										sql="select var_value, addl_value  from finparm "
															+"          where prd_code = '999999' and var_name ='FINCHG_START_DATE' " ;
										pstmt = conn.prepareStatement(sql);
										rs = pstmt.executeQuery();
										if( rs.next() )
										{
															varvalue1 = rs.getString("var_value");
															varvalue2 = rs.getString("addl_value");                                                  
										}
										//System.out.println("varvalue1>>>>>>>>"+varvalue1);
										//System.out.println("varvalue2>>>>>>>>"+varvalue2);
										rs.close();
										rs=null;
										pstmt.close();
										pstmt=null;
										/*if(varvalue2 == null || varvalue2.trim().length()== 0 )
										{
															lsFromdateStr = varvalue1 ;
										}
										else
										{
															lsFromdateStr = varvalue1 + varvalue2 ;
										}*/
										//lsFromdateStr = genericUtility.getValidDateString(lsFromdateStr,genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat());
										//lsFromdateDt = java.sql.Timestamp.valueOf(lsFromdateStr + " 00:00:00");
										/*if ( !"NULLFOUND".equalsIgnoreCase( lsFromdateStr )  && (lsFromdateStr.trim().length() > 0))
										{
															frDateStr = genericUtility.getValidDateString(frDate.toString(),genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat());
															//frDate = java.sql.Timestamp.valueOf(frDateStr + " 00:00:00");
															timdifferance = genericUtility.timeDiff(frDate,lsFromdateDt);
															if(timdifferance <0)
															{
																				frDateStr = lsFromdateStr ;
															}                                                  
										}*/          
										if (  varvalue2 !=null &&(varvalue2.trim().length() > 0) )
										{
												//System.out.println("varvalue2.toString()>>>>>>>>"+varvalue2.toString());                                                  
												java.sql.Timestamp  lsFromdateDate = Timestamp.valueOf(genericUtility.getValidDateString(varvalue2, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat()) + " 00:00:00.0");
																																					
												java.sql.Timestamp frDatedate = Timestamp.valueOf(genericUtility.getValidDateString(frDateStr.toString(), genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat()) + " 00:00:00.0");
												
												if(frDatedate.compareTo (lsFromdateDate) < 0 )
												{
																	frDateStr = lsFromdateStr ;
																	frDateStr = genericUtility.getValidDateString(frDateStr.toString(),genericUtility.getDBDateFormat(),genericUtility.getApplDateFormat());
																	System.out.println("frDateStr>>>>>>>>"+frDateStr);
												}                                                  
										}
							}          
							sql=" select var_value  "
										+ "from finparm  "
										+ " where          var_name='TRANTYPE_FINCHRGCALC' "
										+" and  prd_code='999999' " ;
										pstmt = conn.prepareStatement(sql);
										rs = pstmt.executeQuery();
										if( rs.next() )
										{
															varValue = rs.getString("var_value")==null?"":rs.getString("var_value").trim();
										}
										rs.close();
										rs=null;
										pstmt.close();
										pstmt = null;                                                  
							
							sql=" select var_value,addl_value  "
										+ "from finparm  "
										+ " where          var_name='MIN_FINCHG_AR' "
										+" and  prd_code='999999' " ;
										pstmt = conn.prepareStatement(sql);
										rs = pstmt.executeQuery();
										if( rs.next() )
										{
															varValueMinFin = rs.getString("var_value")==null?"":rs.getString("var_value").trim();
															addlValueMinFin = rs.getString("addl_value")==null?"":rs.getString("addl_value").trim();
										}
										//System.out.println("varValueMinFin>>>>>>>>"+varValueMinFin);
										//System.out.println("addlValueMinFin>>>>>>>>"+addlValueMinFin);
										rs.close();
										rs=null;
										pstmt.close();
										pstmt = null;                                                                                                    
							sql=" select var_value ,addl_value "
									+ "from finparm  "
									+ " where          var_name='ACCT_AR_FINCHG_AR' "
									+" and  prd_code='999999' " ;
									pstmt = conn.prepareStatement(sql);
									rs = pstmt.executeQuery();
									if( rs.next() )
									{
														varvalue1 = rs.getString("var_value")==null?"":rs.getString("var_value").trim();
														varvalue2 = rs.getString("addl_value")==null?"":rs.getString("addl_value").trim();
									}
									//System.out.println("varvalue1>>>>>>>>"+varvalue1);
									//System.out.println("varvalue2>>>>>>>>"+varvalue2);
									rs.close();
									rs=null;
									pstmt.close();
									pstmt = null;                                                  
							// end of code 
							//sql = "select site_code from  site " ;
							//sql= "select * from disAUTONEARCHARGESITE
							String xtraParams = getXtraParams( userInfoDom , siteCode ,   conn );
							System.out.println("xtraParams...\n"+xtraParams);
							/*Changes Done By ashwin on 31/07/10  - Begin
							sql = " SELECT VAR_VALUE  FROM FINPARM  WHERE  PRD_CODE='999999' AND VAR_NAME='AUTOFINCHARGESITE' " ;
							pstmt = conn.prepareStatement(sql);
							rs = pstmt.executeQuery();
							if(rs.next())
							{
												 varName = rs.getString("var_value");
							}
							rs.close();
							pstmt.close();
							rs=null;
							pstmt = null;          
							stringTokenizer = new  StringTokenizer(varName ,",");*/

						//Changes Done By ashwin on31/07/10  - End
						//So as to get Sites from scheduler ActualParameter Instead of FINPARM
						 stringTokenizer = new  StringTokenizer(finSites ,",");
						//Changes Done By ashwin on 7/31/2010
						 while(stringTokenizer.hasMoreElements())
						 {
								filterString.append(stringTokenizer.nextToken()).append("\t");
								filterString.append(frDateStr).append("\t");                                        
								filterString.append(drnoteDateStr).append("\t");
								filterString.append(varValueMinFin + addlValueMinFin).append("\t");
								filterString.append(drnoteDate).append("\t");                                        
								filterString.append(varvalue1).append("\t");
								filterString.append(varvalue1).append("\t");                                        
								filterString.append("0").append("\t");
								filterString.append("Z").append("\t");
								filterString.append("Y").append("\t");
								filterString.append("Y").append("\t");
								filterString.append(varValue ).append("\t");
								filterString.append("0").append("\t");
								filterString.append("\n");
								System.out.println("frDateStr>>>2>>>>>"+frDateStr);
								System.out.println("Data sent ["+filterString.toString() + "]"); 
								// added chgUse in callNvo() on 08/10/09 for xtrapram
								retString = callNvo( filterString.toString(), "finance_charge_calc", "pr_default_1",xtraParams, conn );                    
								// end 
								filterString.setLength(0);
							}
				}
				catch(Exception e)
				{
						e.printStackTrace();
				}
			 return "";
			} // end of schedule          
			public String callNvo( String filterData, String objName, String serviceCode,String xtraParams , Connection conn )  throws ITMException
			{	
					String methodName = "";
					String retString = "";                    
					String serviceURI = "";
					String actionURI = "";
					String selectSql = "";
					String businessObj = "";          
					PreparedStatement pStmt = null;
					ResultSet rs = null;                    
					try
					{
							//businessObj = "nvo_bo_finance_charge_calc";
							selectSql = "SELECT comp_name FROM SYSTEM_EVENTS WHERE OBJ_NAME = ? AND service_code = ? ";
							//System.out.println("\nselectSql :: "+selectSql);
							pStmt = conn.prepareStatement(selectSql);
							pStmt.setString(1,objName);
							pStmt.setString(2,serviceCode);
							rs = pStmt.executeQuery();
							if ( rs.next() )
							{
												businessObj = rs.getString( "comp_name" );
							}
							System.out.println("\n businessObj :: ["+businessObj+"]");                              
							rs.close();
							rs=null;
							pStmt.close();
							pStmt = null;          
							selectSql = "SELECT SERVICE_URI, METHOD_NAME FROM SYSTEM_EVENT_SERVICES WHERE SERVICE_CODE = ? ";
							System.out.println("\nselectSql :: "+selectSql);
							pStmt = conn.prepareStatement(selectSql);
							pStmt.setString(1,serviceCode);                              
							rs = pStmt.executeQuery();
							if ( rs.next() )
							{
												serviceURI = rs.getString( "SERVICE_URI" );
												methodName = rs.getString( "METHOD_NAME" );
							}
							rs.close();
							rs=null;
							pStmt.close();
							pStmt = null;
							System.out.println("\n serviceURI :: ["+serviceURI+"]");
							System.out.println("\n methodName :: ["+methodName+"]");                              
							actionURI = "http://NvoServiceurl.org/"+methodName;                              
							System.out.println("\n actionURI :: ["+actionURI+"]");
							 Service service = new Service();
							Call call = ( Call )service.createCall();
							call.setTargetEndpointAddress(new java.net.URL(serviceURI));                              

							call.setOperationName( new javax.xml.namespace.QName("http://NvoServiceurl.org", methodName ) );
							call.setUseSOAPAction(true);
							call.setSOAPActionURI(actionURI); 
							Object[] aobj = new Object[4];
							
							call.addParameter( new javax.xml.namespace.QName("http://NvoServiceurl.org", "component_name"), XMLType.XSD_STRING, ParameterMode.IN);
							call.addParameter( new javax.xml.namespace.QName("http://NvoServiceurl.org", "tab_xml_data_1"), XMLType.XSD_STRING, ParameterMode.IN);
							call.addParameter( new javax.xml.namespace.QName("http://NvoServiceurl.org", "dummy"), XMLType.XSD_STRING, ParameterMode.IN);
							call.addParameter( new javax.xml.namespace.QName("http://NvoServiceurl.org", "xtra_params"), XMLType.XSD_STRING, ParameterMode.IN);

							aobj[0] = new String(businessObj);
							aobj[1] = new String(filterData);
							aobj[2] = new String( "" );
							aobj[3] = new String( xtraParams );// passed blank as It can not be created from scheduler
							
							call.setReturnType(XMLType.XSD_STRING);
							retString = (String)call.invoke( aobj );
							System.out.println("Return value [" + retString +"]");  // leave this 
					}
					catch(Exception e)
					{
							e.printStackTrace();
							throw new ITMException(e);
					}
					finally
					{
							try
							{
									if(pStmt != null )
									{
										pStmt.close();
										pStmt = null;
									}
							}
							catch(Exception e)
							{e.printStackTrace();}
					}
					return retString ;

		  }          
		  private Timestamp getCurrdateAppFormat()
		  {
				 String s = "";          
				 Timestamp timestamp = null;                    
				 GenericUtility genericUtility = GenericUtility.getInstance();
				 try
				 {
						 java.util.Date date = null;
						 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");
																//System.out.println("timestamp is ==>"+timestamp);
				 }
				 catch(Exception exception)
				 {
						 System.out.println("Exception in  getCurrdateAppFormat " + exception.getMessage());
				 }
				 return timestamp;
		  }
		  private String getXtraParams(Document userInfoDom ,String siteCode ,  Connection conn )throws Exception
		  {
					StringBuffer xtraParamsBuff = new StringBuffer();
					PreparedStatement pstmt =null;
					ResultSet rs = null;
					String XTRA_PARAMS_SEPARATOR = "~~";
					String loginCode="",loginEmpCode="",loginSiteCode="",entityCode="",profileId="",userType="";
					String runMode="",chgTerm="",chgUser="",remoteHost="",sql="", charEnc="";

					loginCode = userInfoDom.getElementsByTagName( "loginCode" ).item(0).getFirstChild().getNodeValue();
					charEnc = userInfoDom.getElementsByTagName( "charEnc" ).item(0).getFirstChild().getNodeValue();
					remoteHost = userInfoDom.getElementsByTagName( "remoteHost" ).item(0).getFirstChild().getNodeValue();                    
					
					sql="select emp_code,entity_code,profile_id,user_type,chg_term,chg_user from users where code = ? ";
					 pstmt=conn.prepareStatement(sql);
					pstmt.setString(1,loginCode);
					//pstmt.setString(2,siteCode);
					//pstmt.setString(3,itemCode);
					 rs =  pstmt.executeQuery();
					if(rs.next())
					{
							loginEmpCode = rs.getString("emp_code")==null?"":rs.getString("emp_code");
							entityCode = rs.getString("entity_code")==null?"":rs.getString("entity_code");
							profileId = rs.getString("PROFILE_ID")==null?"":rs.getString("PROFILE_ID");
							userType = rs.getString("USER_TYPE")==null?"":rs.getString("USER_TYPE");
							chgTerm = rs.getString("CHG_TERM")==null?"":rs.getString("CHG_TERM");
							chgUser = rs.getString("CHG_USER")==null?"":rs.getString("CHG_USER");
					}
					pstmt.close();
					pstmt=null;
					rs.close();
					rs=null;
					xtraParamsBuff.append("loginCode=" + loginCode);
					xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("loginEmpCode=" + loginEmpCode);
					xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("loginSiteCode=" + siteCode);
					xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("entityCode=" + entityCode);
					xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("profileId=" + profileId);
					xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("userType=" + userType);
					xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("runMode=I");
					//xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("user_lang=" + this.user_lang);
					//xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("user_country=" + this.user_country);
					xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("charEnc=" +charEnc );                    
					
					xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("termId="+remoteHost);
					// changes by madhup 10/02/07
					xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("chgTerm=" + chgTerm);
					return xtraParamsBuff.toString();
		  }
} 