/********************************************************
	Title 	 : MiscPayConfSch[F14FSUN003]
	Date  	 : 18/SEP/14
	Developer: Sagar M.
 ********************************************************/
package ibase.webitm.ejb.fin;
import ibase.scheduler.utility.interfaces.Schedule;
import java.rmi.RemoteException;
import java.util.*;
import java.util.Date;
import java.sql.*;
import java.io.*;

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.omg.CORBA.ORB;
import org.w3c.dom.*;



import java.util.Properties;

import javax.swing.text.NumberFormatter;
import javax.xml.parsers.*;
import javax.xml.rpc.ParameterMode;
import javax.ejb.*;
import javax.naming.InitialContext;

import ibase.webitm.utility.ITMException;
import ibase.webitm.ejb.*;
import ibase.webitm.ejb.dis.DistCommon;
import ibase.webitm.ejb.fin.GenerateReceiptPrc;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.TransIDGenerator;
import ibase.utility.BaseException;
import ibase.utility.CommonConstants;
import ibase.utility.UserInfoBean;
import ibase.ejb.*;
import ibase.system.config.*;

import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.math.*;
import java.net.InetAddress;
import ibase.webitm.ejb.sys.UtilMethods;

public class MiscPayConfSch implements Schedule
{
	GenericUtility genericUtility = GenericUtility.getInstance();
	//FileOutputStream fos1 = null;
	File filePtr ;
	File logDir ;
	String logDirName = "";
	@Override
	public String schedule(String scheduleParamXML)throws Exception
	{
		ConnDriver connDriver = new ConnDriver();
		Connection conn = null;
		conn = connDriver.getConnectDB("DriverITM");
		connDriver = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String queryString="";
		String tranId="";
		java.sql.Timestamp currDate = null;
		String currAppdate ="";
		String valuexmlString="";
		String retString="";
		ITMDBAccessEJB itmDBAccessEJB = null;
		ibase.utility.UserInfoBean userInfo = null;
		String loginSiteCode="";
		String strToWrite="";
		SimpleDateFormat sdf1 = new SimpleDateFormat(genericUtility.getDBDateFormat());
		String currTime = null;
		Calendar calendar = Calendar.getInstance();
		currTime = sdf1.format(new Timestamp(System.currentTimeMillis())).toString();
		currTime = currTime.replaceAll("-","");
		
		try
		{

			if(! CommonConstants.DEBUG_LEVEL.equals("0")) 
			{
				if(CommonConstants.J2EE_VERSION.equals("1"))
				{
					logDirName =  CommonConstants.JBOSSHOME  + File.separator + "log" ;
				}
				else if(CommonConstants.J2EE_VERSION.equals("2"))
				{
					logDirName =  CommonConstants.JBOSSHOME   + File.separator + "server"+ File.separator +"default"+ File.separator +"log" ;
				}
				logDir = new File(logDirName);
				filePtr = new File(logDirName+ File.separator + "miscpaysch" + currTime + ".log");
			}

			Document dom = null;
			String xtraParams = "",source="";
			Node currDetail = null ;
			int noOfParam=0;
			System.out.println("************ ["+scheduleParamXML+"]");
			userInfo = new ibase.utility.UserInfoBean( scheduleParamXML );
			loginSiteCode = userInfo.getSiteCode();
			
			java.util.Date today=new java.util.Date();
			Calendar c = Calendar.getInstance(); 
			c.setTime(today); 
			today = c.getTime();
			SimpleDateFormat sdf=new SimpleDateFormat(genericUtility.getApplDateFormat());
			currAppdate=sdf.format(today);
			System.out.println(">>>>>>> loginSiteCode:"+loginSiteCode);
			System.out.println(">>>>>>> loginEmpCode:"+ userInfo.getEmpCode());
			//xtraParams = "loginCode="+userInfo.getLoginCode()+"~~termId="+userInfo.getRemoteHost()+"~~loginSiteCode="+loginSiteCode;
			xtraParams = "loginCode="+userInfo.getLoginCode()+"~~termId="+userInfo.getRemoteHost()+"~~loginSiteCode="+loginSiteCode+"~~loginEmpCode="+userInfo.getEmpCode();
			itmDBAccessEJB = new ITMDBAccessEJB();
			
			sdf1= new SimpleDateFormat(genericUtility.getDBDateFormat());
			java.util.Date currentDate = new java.util.Date();
			Timestamp newsysDate = java.sql.Timestamp.valueOf( sdf1.format(currentDate)+" 00:00:00.0");
			System.out.println(">>>> newsysDate is:"+newsysDate);
			
			queryString = "SELECT TRAN_ID FROM MISC_PAYMENT WHERE CONFIRMED='N' AND WF_STATUS='S' AND REF_DATE= ? ";
			pstmt = conn.prepareStatement(queryString);
			pstmt.setTimestamp(1, newsysDate );
			rs=pstmt.executeQuery();
			while(rs.next())
			{
				tranId=rs.getString("TRAN_ID");
				valuexmlString=tranId+"\t"+currAppdate;
				System.out.println(">>>>>>>>>>>Found Tran id for Confirm:"+tranId);
				String forcedFlag="N";
				retString=payConfirm("misc_pay",tranId,xtraParams,forcedFlag,conn);
				
				if((retString != null ) && (retString.indexOf("VTSUCC1") > -1))
				{
					System.out.println(">>>>>>>>>retString.indexOf(VTSUCC1) :"+retString.indexOf("VTSUCC1"));
					conn.commit();
					System.out.println(">>>>After Commit Confirm Completed:"+tranId);
					if(retString.indexOf("VTSUCC1") > -1)
					{
						strToWrite = " ["+ tranId + "] success ";
					}
					else
					{
						strToWrite = " ["+tranId+"] return ["+retString+"]";
					}
					
				}
				else 
				{
					strToWrite = " ["+tranId+"] return ["+retString+"]";
					conn.rollback();
					System.out.println(">>>>>>>>>>Confirm Failed:"+tranId);
				}
				
				if(! CommonConstants.DEBUG_LEVEL.equals("0")) 
				{
					writeLog( filePtr, strToWrite, true );
				}
				//System.out.println(">>>>strToWrite-----"+strToWrite);
				//fos1.write(strToWrite.getBytes());
			}
			rs.close();
			rs=null;
			pstmt.close();
			pstmt=null;
			
		}catch(Exception e)
		{
			System.out.println(">>>>>>>>>>>>>In catch:");
			try
			{
			
				if(! CommonConstants.DEBUG_LEVEL.equals("0")) 
				{
					strToWrite = " ["+tranId+"] return ["+e.getMessage()+"]";
					writeLog( filePtr, strToWrite, true );
				}

				if(conn!=null)
				{
					conn.rollback();
				}
				e.printStackTrace();
				conn.rollback();
			}
			catch(Exception e1)
			{
				System.out.println( "Exception"+e1.getMessage());

			}
		}
		finally
		{
			try
			{
				if(conn!=null)
				{
					conn.close();
					conn=null;
				}
			}
			catch(Exception e)
			{
				System.out.println( "Exception"+e.getMessage());

			}
		}
		return "";

	}

	@Override
	public String schedule(HashMap arg0) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String schedulePriority(String arg0) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}
	public String payConfirm(String businessObj,String tranId,String xtraParams,String forcedFlag, Connection conn) throws Exception, ITMException
	{
		String methodName = "";
		String compName = "";
		String retString = "";
		String serviceCode = "";
		String serviceURI = "";
		String actionURI = "";
		String sql = "";
		PreparedStatement pstmt = null;
		ResultSet rs = null;

		try
		{
			
			methodName = "gbf_post";
			actionURI = "http://NvoServiceurl.org/" + methodName;

			sql = "SELECT SERVICE_CODE,COMP_NAME FROM SYSTEM_EVENTS WHERE OBJ_NAME = ? AND EVENT_CODE = 'pre_confirm' ";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,businessObj);
			rs = pstmt.executeQuery();
			if ( rs.next() )
			{
				serviceCode = rs.getString("SERVICE_CODE");
				compName = rs.getString("COMP_NAME");
			}
			System.out.println(">>>Misc Payments serviceCode = "+serviceCode+" compName "+compName);
			sql = "SELECT SERVICE_URI FROM SYSTEM_EVENT_SERVICES WHERE SERVICE_CODE = ? ";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,serviceCode);
			rs = pstmt.executeQuery();
			if ( rs.next() )
			{
				serviceURI = rs.getString("SERVICE_URI");
			}
			System.out.println(">>>Misc Payments serviceURI = "+serviceURI+" compName = "+compName);
			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", "tran_id"), XMLType.XSD_STRING, ParameterMode.IN);
			call.addParameter( new javax.xml.namespace.QName("http://NvoServiceurl.org", "xtra_params"), XMLType.XSD_STRING, ParameterMode.IN);
			call.addParameter( new javax.xml.namespace.QName("http://NvoServiceurl.org", "forced_flag"), XMLType.XSD_STRING, ParameterMode.IN);

			aobj[0] = new String(compName);
			aobj[1] = new String(tranId);
			aobj[2] = new String(xtraParams);
			aobj[3] = new String(forcedFlag);
			
			System.out.println("@@@@@@ call.setReturnType(XMLType.XSD_STRING) executed........");
			call.setReturnType(XMLType.XSD_STRING);
			retString = (String)call.invoke(aobj);

			System.out.println(">>>>Confirm Complete Return string from NVO is:==>["+retString+"]");
		}
		catch(Exception e)
		{
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{		
			try{


				if (pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
				/*if( conn != null ){
					conn.close();
					conn = null;
				}*/
			}
			catch(Exception e)
			{
				System.out.println("Exception inCalling confirmed");
				e.printStackTrace();
				try{
					conn.rollback();

				}catch (Exception s)
				{
					System.out.println("Unable to rollback");
					s.printStackTrace();
				}
				throw new ITMException(e);
			}

		}
		return retString;
	}
	
	void writeLog(File f,String Msg,boolean flag) throws Exception
	{
	

		try{
			SimpleDateFormat sdf1 = new SimpleDateFormat(genericUtility.getDBDateFormat());
			String currTime = null;
			Calendar calendar = Calendar.getInstance();
			currTime = sdf1.format(new Timestamp(System.currentTimeMillis())).toString();
			currTime = currTime.replaceAll("-","");
			calendar.setTime(new java.sql.Timestamp(System.currentTimeMillis()));

			if(! CommonConstants.DEBUG_LEVEL.equals("0")) 
			{
				PrintWriter pw = new PrintWriter((new FileOutputStream(f,flag)),flag);
				pw.println("{" + currTime  + " " + calendar.get(Calendar.HOUR)+":"+calendar.get(Calendar.MINUTE) + "}\t" + Msg);
				pw.close();
			}
		}
		catch(Exception exWm){exWm.printStackTrace();}
	}

}
