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 VoucherConfScheduler implements Schedule
{
	GenericUtility genericUtility = GenericUtility.getInstance();
	FileOutputStream fos1 = null;
	Calendar calendar = Calendar.getInstance();
	java.util.Date startDate = new java.util.Date(System.currentTimeMillis());
	String startDateStr = null;
	@Override
	public String schedule(String scheduleParamXML)throws Exception,ITMException
	{
		ibase.utility.UserInfoBean userInfo = null;
		String loginSiteCode="",siteCode="";
		try
		{
			Document dom = null;
			String xtraParams = "",siteList="";
			
			Node currDetail = null ;
			int noOfParam=0;
			System.out.println("************ ["+scheduleParamXML+"]");
			userInfo = new ibase.utility.UserInfoBean( scheduleParamXML );
			loginSiteCode = userInfo.getSiteCode();
			System.out.println("intializingLog$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$........."+ intializingLog("Purc_Voucher_conf_log"));
			System.out.println("Site code======**************====> "+loginSiteCode);
			xtraParams = "loginEmpCode="+userInfo.getEmpCode()+"~~loginCode="+userInfo.getLoginCode()+"~~termId="+userInfo.getRemoteHost()+"~~loginSiteCode="+loginSiteCode;
			System.out.println("xtraParams---["+xtraParams+"]");
		    GenericUtility genericUtility=GenericUtility.getInstance();
			System.out.println("scheduleParamXML-----"+scheduleParamXML);
			dom=genericUtility.parseString(scheduleParamXML);
			NodeList paramList = dom.getElementsByTagName( "SCHEDULE" );

			noOfParam = paramList.getLength();            
			NodeList parentNodeList = null,childNodeList = null;
			Node parentNode = null,childNode = null;
			//String DisparmSites = "";
			int childNodeListLength = 0;
			String childNodeName = null;

			parentNodeList = dom.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)
					{
						siteList = checkNull(childNode.getFirstChild().getNodeValue());
					}

				}
			}
			System.out.println("siteList----"+siteList);
			if(siteList.length()>0)
			{
				String siteListArr[]=siteList.split(",");
				if(siteListArr.length>0)
				{
					for(int i=0;i<siteListArr.length;i++)
					{
						siteCode=siteListArr[i];	
						voucherConfirm(siteCode,xtraParams);
					}
					
				}
			}	
		}
		catch (Exception e) 
		{

			System.out.println("Exception :SplitSchedularSOrder :schedule :Exception :==>\n"+e.getMessage());
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if(fos1!=null)
				{
					fos1.close();
					fos1=null;
				}
			}
			catch(Exception e)
			{
				System.out.println( "Exception"+e.getMessage());

			}
		}
		return "";
	}
	private String intializingLog(String fileName)
	{
		String log="intializingLog_Failed";
		String strToWrite = "";
		String currTime = null;
		try{
			SimpleDateFormat sdf1 = new SimpleDateFormat(genericUtility.getDBDateFormat());
			try
			{
				currTime = sdf1.format(new Timestamp(System.currentTimeMillis())).toString();
				currTime = currTime.replaceAll("-","");
				calendar.setTime(new java.sql.Timestamp(System.currentTimeMillis()));
				fileName = fileName+currTime+calendar.get(Calendar.HOUR)+""+calendar.get(Calendar.MINUTE)+".csv";
				fos1 = new FileOutputStream(CommonConstants.JBOSSHOME + File.separator +"EDI"+File.separator+fileName);
				//strToWrite="\"TRANID\",\"START TIME\",\"END TIME\",\"STATUS\"\r\n";
				//fos1.write(strToWrite.getBytes());

			}
			catch(Exception e)
			{
				System.out.println("Exception []::"+e.getMessage());
				e.printStackTrace();
			}
			startDate = new java.util.Date(System.currentTimeMillis());
			calendar.setTime(new java.sql.Timestamp(System.currentTimeMillis()));
			startDateStr = sdf1.format(startDate)+" "+calendar.get(Calendar.HOUR)+":"+calendar.get(Calendar.MINUTE)+":"+calendar.get(Calendar.SECOND);
			fos1.write(("Fetching Records Started At " + startDateStr +"\r\n").getBytes());

		}
		catch(Exception e)
		{
			System.out.println("Exception []::"+e.getMessage());
			e.printStackTrace();
		}

		log ="intializingLog_Successesfull";
		return log;
	}
	
	private String checkNull(String input)
	{
		if (input == null)
		{
			input = "";
		}
		return input;
	}
	 public void voucherConfirm(String siteCode,String xtraParams) throws ITMException
	 {
		 ConnDriver connDriver = new ConnDriver();
		 Connection conn = null;
		 PreparedStatement pstmt=null;
		 ResultSet rs=null;
		 
		 String sql="";
		 String tranId="",retString="";
		 
		 try
		 {
			 conn = connDriver.getConnectDB("DriverITM");
			 connDriver = null;
			 sql="select tran_id from voucher where site_code=? and confirmed='N' and "
			 		+ "tran_id in(select voucher_no from supplier_bill where  case when match_status is null then '1' else match_status end = '3')"
			 		+ " union all select tran_id from voucher where site_code=? and confirmed='N' "
			 		+ "and tran_id not in(select voucher_no from supplier_bill where "
			 		+ "voucher_no is not null) ";
			 pstmt=conn.prepareStatement(sql);
			 pstmt.setString(1,siteCode);
			 pstmt.setString(2,siteCode);
			 rs=pstmt.executeQuery();
			 while(rs.next())
			 {
				 tranId=rs.getString("tran_id");
				 fos1.write(("Purchase Voucher Tran Id is::  [" + tranId +"]\r\n").getBytes());
				 retString=confirmTran("voucher",tranId,xtraParams,"",conn); 
				 fos1.write(("Status is::  [" + retString +"]\r\n").getBytes());
			 }
			 rs.close();
			 rs=null;
			 pstmt.close();
			 pstmt=null;
			 
			 
			 
			 
		 }catch(Exception e)
		 {
			 e.printStackTrace();
			throw new ITMException(e);
		 }
		 finally
		 {
			 if(rs!=null)
			 {
				 try {
					rs.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			 }
			 if(pstmt!=null)
			 {
				 try {
					pstmt.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			 }
			 if(conn!=null)
			 {
				 try {
					conn.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			 }
			 rs=null;
			 pstmt=null;
			 conn=null;
			 
			 
		 }
		 
		 
		 
	 }
	public String confirmTran(String businessObj,String tranId,String xtraParams,String forceFlag,Connection conn) throws ITMException
		{
			String methodName = "";
			String compName = "";
			String retString = "";
			String serviceCode = "";
			String serviceURI = "";
			String actionURI = "";
			String sql = "";
			PreparedStatement pstmt = null;
			ResultSet rs = null;
			//System.out.println("confirmJournalVoucher(String businessObj, String tranIdFr,String xtraParams, String forcedFlag, Connection conn) called >>><!@#>");

			try
			{
				//ConnDriver connDriver = new ConnDriver();
				//conn = connDriver.getConnectDB("DriverITM");

				//methodName = "gbf_post";
				

				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");
				}
				rs.close();
				rs=null;
				pstmt.close();
				pstmt=null;
				System.out.println("serviceCode = "+serviceCode+" compName "+compName);
				sql = "SELECT SERVICE_URI,METHOD_NAME FROM SYSTEM_EVENT_SERVICES WHERE SERVICE_CODE = ? ";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1,serviceCode);
				rs = pstmt.executeQuery();
				if ( rs.next() )
				{
					methodName= rs.getString("METHOD_NAME");
					serviceURI = rs.getString("SERVICE_URI");
				}
				rs.close();
				rs=null;
				pstmt.close();
				pstmt=null;
				actionURI = "http://NvoServiceurl.org/" + methodName;
				System.out.println("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("");
				
				//System.out.println("@@@@@@@@@@loginEmpCode:" +genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginEmpCode")+":");
				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;
		}

		
	@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;
	}
	
	
	

}

