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 VoucherGenScheduler 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_gen_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];	
						generateVoucher(siteCode,xtraParams);
					}
					
				}
			}	
		}
		catch (Exception e) 
		{

			System.out.println("Exception :PoRcpGenScheduler :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 generateVoucher(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 porcp where confirmed='Y' and site_code=? and case when vouch_created is null then 'N' else vouch_created end ='N'";
			 pstmt=conn.prepareStatement(sql);
			 pstmt.setString(1,siteCode);
			 rs=pstmt.executeQuery();
			 while(rs.next())
			 {
				 tranId=rs.getString("tran_id");
				 fos1.write(("Purchase Receipt Tran Id is::  [" + tranId +"]\r\n").getBytes());
				 InvAcct invAcct = new InvAcct();
					retString = invAcct.acctPoRcpt(tranId, conn);
					if (retString != null && "CREATE-VOUCHER".equals(retString.trim()))
					{
						CreatePoRcpVoucher createVouc = new CreatePoRcpVoucher();
						retString = createVouc.createPoRcpVoucher(tranId,xtraParams, conn);
						fos1.write(("Status is::  [" + retString +"]\r\n").getBytes());
						if( retString.indexOf("Success") != -1 )
						{
							conn.commit();
						}
						else
						{
							conn.rollback();
						}
					} 
			 }
			 rs.close();
			 rs=null;
			 pstmt.close();
			 pstmt=null;
			 
		 }catch(Exception e)
		 {
			
			 try {
				conn.rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			 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;
			 
			 
		 }
		 
		 
		 
	 }
	
	@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;
	}
	
	
	

}


