package ibase.webitm.ejb.mfg;
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 QCOrderCreationSch implements Schedule
{
	GenericUtility genericUtility = GenericUtility.getInstance();
	FileOutputStream fos1 = null;
	@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 siteCode="";
		java.sql.Timestamp currDate = null;
		String currAppdate ="";
		
		String valuexmlString="";
		String retString="";
		ITMDBAccessEJB itmDBAccessEJB = null;
		ibase.utility.UserInfoBean userInfo = null;
		String loginSiteCode="";
		String strToWrite="";
		
		try
		{
			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); 
			//c.add(Calendar.DATE, 1);
			today = c.getTime();
			
			System.out.println("Site code======**************====> "+loginSiteCode);
			//xtraParams = "loginCode="+userInfo.getEmpCode()+"~~termId="+userInfo.getRemoteHost()+"~~loginSiteCode="+loginSiteCode;
			//Changed by Manoj dtd 29/01/2014 to set loginCode in xtraParams
			xtraParams = "loginCode="+userInfo.getLoginCode()+"~~termId="+userInfo.getRemoteHost()+"~~loginSiteCode="+loginSiteCode;
			
			itmDBAccessEJB = new ITMDBAccessEJB();
			//currDate = new java.sql.Timestamp(System.currentTimeMillis()) ;
			//currAppdate = new SimpleDateFormat(genericUtility.getApplDateFormat()).format(currDate);
			SimpleDateFormat sdf=new SimpleDateFormat(genericUtility.getApplDateFormat());
			currAppdate=sdf.format(today);
			System.out.println("intializingLog$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$........."+ intializingLog("QCORDER_CREATE_STATUS"));
			
			queryString="SELECT SITE_CODE FROM SITE WHERE SITE_TYPE='F'";
			//queryString="SELECT SITE_CODE FROM SITE WHERE SITE_CODE='TA821'";
			pstmt=conn.prepareStatement(queryString);
			rs=pstmt.executeQuery();
			while(rs.next())
			{
				siteCode=rs.getString("SITE_CODE");
				valuexmlString=siteCode+"\t"+currAppdate;
				retString=createQCOrder("create_qord",valuexmlString,xtraParams,conn);
				System.out.println("retString----"+retString);
				
				
				
				if((retString != null ) &&  ((retString.indexOf("VPSUCC1") > -1 || retString.indexOf("VTQCINFO") > -1)))
				{
					conn.commit();
					System.out.println("--process completed--");
					if(retString.indexOf("VPSUCC1") > -1)
					{
						strToWrite = "QC Order Creation(Retest) for Site "+siteCode+" is :  No Data found \r\n\r\n";
					}
					else
					{
						strToWrite = "QC Order Creation(Retest) for Site "+siteCode+" is :  "+retString+" \r\n\r\n";
					}
					//retString = itmDBAccessEJB.getErrorString("","VPSUCC1    ","","",conn);
				}
				else 
				{
					strToWrite = "QC Order Creation(Retest) for Site "+siteCode+" is :  "+retString+" \r\n\r\n";
					
					conn.rollback();
					System.out.println("--process not completed--");
					//retString = itmDBAccessEJB.getErrorString("","VTPRCERR ","","",conn);
				}
				System.out.println("strToWrite-----"+strToWrite);
				fos1.write(strToWrite.getBytes());
				
				
			}
			rs.close();
			rs=null;
			pstmt.close();
			pstmt=null;
			
		}catch(Exception e)
		{
			if(conn!=null)
			{
				conn.rollback();
				
			}
			e.printStackTrace();
			conn.rollback();
		}
		finally
		{
			if(conn!=null)
			{
				conn.commit();
				conn.close();
				conn=null;
				pstmt.close();
				pstmt=null;
			}
			try
			{
				if(fos1!=null)
				{
					fos1.close();
					fos1=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 createQCOrder(String businessObj, String valuexmlString,String xtraParams,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_process";
			actionURI = "http://NvoServiceurl.org/" + methodName;

			sql = "SELECT SERVICE_CODE,COMP_NAME FROM SYSTEM_EVENTS WHERE OBJ_NAME = ? AND EVENT_CODE = 'process' ";
			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("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("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", "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(compName);
			aobj[1] = new String(valuexmlString);
			aobj[2] = new String("");
			aobj[3] = new String(xtraParams);
			
			//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;
	}
	private String intializingLog(String fileName)
	{
		String log="intializingLog_Failed";
		String strToWrite = "";
		String currTime = null;
		String currAppdate="";
		try{
			
			SimpleDateFormat sdf1 = new SimpleDateFormat(genericUtility.getDBDateFormat());
			try
			{
				
				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);
				currAppdate=currAppdate.replace("/","_");
				System.out.println("currAppdate-------"+currAppdate);
				fileName = fileName+currAppdate+".log";
				fos1 = new FileOutputStream(CommonConstants.JBOSSHOME + File.separator +"log"+File.separator+fileName);
				fos1.write(("Fetching Records Started At " + currAppdate +"\r\n").getBytes());
			
			}
			catch(Exception e)
			{
				System.out.println("Exception []::"+e.getMessage());
				e.printStackTrace();
			}
			

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

		log ="intializingLog_Successesfull";
		return log;
	}
	

}
