/********************************************************
	Title : EcollectionSchedule[F14ISUN014]
	Date  : 17/02/15
	Developer: Chandrashekar

 ********************************************************/
package ibase.webitm.ejb.fin;
import ibase.scheduler.utility.interfaces.Schedule;
import java.util.*;
import java.util.Date;
import java.sql.*;
import org.w3c.dom.*;



import javax.naming.InitialContext;
import ibase.webitm.utility.ITMException;
import ibase.webitm.ejb.*;
import ibase.webitm.ejb.fin.adv.ReceiptAdvConf;
import ibase.webitm.utility.GenericUtility;
import ibase.system.config.*;

import java.text.SimpleDateFormat;
import ibase.utility.E12GenericUtility;

public class EcollectionSchedule implements Schedule
{
	
	String chgUser = null;
	String chgTerm = null;
	static long count_records=0;
	boolean isError = false;
	String loginSiteCode = "";
	String retString="";
	
	public static void main(String args[])
	{
		EcollectionSchedule ecs=new EcollectionSchedule();
		System.out.println("Main Method Calling******************************************************88");
	}
	
	public String schedulePriority( String wrkflwPriority )throws Exception
	{
		return "";
	}
	public String schedule(HashMap map)throws Exception
	{
		return "";
	}
	public String schedule(String scheduleParamXML)throws Exception
	{
		String siteCode = "",actualLoginSiteCode="",errString="";
		String xtraParams = "";
		ibase.utility.UserInfoBean userInfo = null;
		try
		{
			System.out.println("************ ["+scheduleParamXML+"]");
			userInfo = new ibase.utility.UserInfoBean( scheduleParamXML );
			siteCode = userInfo.getSiteCode();
			xtraParams = "loginEmpCode="+userInfo.getEmpCode()+"~~termId="+userInfo.getRemoteHost()+"~~loginSiteCode="+loginSiteCode;
			
			GenericUtility genericUtility=GenericUtility.getInstance();
			Document dom=genericUtility.parseString(scheduleParamXML);
			
			NodeList paramList = dom.getElementsByTagName( "SCHEDULE" );
           // Node currDetail = null ;            
           // int 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)
					{
						actualLoginSiteCode=childNode.getFirstChild().getNodeValue();
					}
								
				}
			}
			System.out.println("ActualLoginSiteCode----["+actualLoginSiteCode+"]");
			if(("null".equals(actualLoginSiteCode) || actualLoginSiteCode.trim().length() == 0  ))
			{
				siteCode = userInfo.getSiteCode();
				System.out.println("Site code >>>>>>>>>> "+siteCode);
				errString= insertReceipt(siteCode,scheduleParamXML,xtraParams);
			}
			else
			{
				String[] arrStr =actualLoginSiteCode.split(",");
				int len =arrStr.length;
				for(int i =0;i<len;i++)
				{
						loginSiteCode =arrStr[i];
						System.out.println("loginSiteCode>>>>>>>>"+loginSiteCode);
						errString=	insertReceipt(loginSiteCode,scheduleParamXML,xtraParams);
				}		
			}
			
			
		}
		catch(Exception e)
		{
			throw new Exception(e);
		}
		System.out.println("errString>>>["+errString+"]");
		return errString;
	}
	public String insertReceipt(String siteCode , String scheduleParamXML,String xtraParams) throws Exception
	{
		
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		PreparedStatement pstmt1 = null;
		ResultSet rs1 = null;
		String sql="";
		String tranId="";
		String tranDate =null;
		String bankCode = "",refNo="",custCode="",tranType="",rcpMode="",finEntity="",remarks="";
		String sql1="",refSer="",lineNoRef="";
		String errString ="",xmlString="";
		double rcpAmt=0,bankAmount=0,rcpAmtDet=0;
		int cnt=0,lineNo=0;
		Date refDate=null,effDate=null;
		E12GenericUtility e12GenericUtility = new E12GenericUtility();
		SimpleDateFormat sdf = new SimpleDateFormat(e12GenericUtility.getApplDateFormat());
		ReceiptAdvConf ReceiptAdv = new ReceiptAdvConf();
		try
		{
			ConnDriver connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("DriverITM");
			connDriver = null;
			conn.setAutoCommit(false);

			SimpleDateFormat simpleDateFormat = new SimpleDateFormat(e12GenericUtility.getApplDateFormat());
			java.util.Calendar cal = java.util.Calendar.getInstance();
			tranDate = simpleDateFormat.format(cal.getTime());

			sql = "select bank_code,ref_no,chq_amt,cust_code,tran_type,rcp_mode,ref_date,eff_date,remarks,tran_id from " + " receipt_form where  confirmed='Y' and status='C' and site_code= ?  ";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, siteCode);
			rs = pstmt.executeQuery();
			while (rs.next())
			{

				bankCode = rs.getString("bank_code");
				refNo = rs.getString("ref_no");
				custCode = rs.getString("cust_code");
				rcpAmt = rs.getDouble("chq_amt");
				tranType = rs.getString("tran_type");
				rcpMode = rs.getString("rcp_mode");
				refDate = rs.getDate("ref_date");
				effDate = rs.getDate("eff_date");
				remarks = rs.getString("remarks");
				tranId = rs.getString("tran_id");

				System.out.println("receipt form tranId:::::::::" + tranId);

				sql1 = " select fin_entity from site where site_code=? ";
				pstmt1 = conn.prepareStatement(sql1);
				pstmt1.setString(1, siteCode);
				rs1 = pstmt1.executeQuery();
				if (rs1.next())
				{
					finEntity = rs1.getString("fin_entity");
				}
				rs1.close();
				rs1 = null;
				pstmt1.close();
				pstmt1 = null;

				finEntity = finEntity == null ? "" : finEntity.trim();

				sql1 = " select amount from bank_statement where site_code=? and bank_code= ?  and ref_no= ?";
				pstmt1 = conn.prepareStatement(sql1);
				pstmt1.setString(1, siteCode);
				pstmt1.setString(2, bankCode);
				pstmt1.setString(3, refNo);
				rs1 = pstmt1.executeQuery();
				if (rs1.next())
				{
					bankAmount = rs1.getDouble("amount");
				}
				rs1.close();
				rs1 = null;
				pstmt1.close();
				pstmt1 = null;

				System.out.println("bankAmount>>>>>>[" + bankAmount + "]rcpAmt[" + rcpAmt + ']');
				if (rcpAmt == bankAmount)
				{
					StringBuffer xmlBuff = new StringBuffer();
					StringBuffer advBuff = new StringBuffer();
					errString = "";

					xmlBuff.append("<?xml version='1.0' encoding='ISO-8859-1'?>\n");
					xmlBuff.append("<DocumentRoot>");
					xmlBuff.append("<description>").append("Datawindow Root").append("</description>");
					xmlBuff.append("<group0>");
					xmlBuff.append("<description>").append("Group0 description").append("</description>");
					xmlBuff.append("<Header0>");

					xmlBuff.append("<objName><![CDATA[").append("receipt_adv").append("]]></objName>");
					xmlBuff.append("<pageContext><![CDATA[").append("1").append("]]></pageContext>");
					xmlBuff.append("<objContext><![CDATA[").append("1").append("]]></objContext>");
					xmlBuff.append("<editFlag><![CDATA[").append("A").append("]]></editFlag>");
					xmlBuff.append("<focusedColumn><![CDATA[").append("").append("]]></focusedColumn>");
					xmlBuff.append("<action><![CDATA[").append("SAVE").append("]]></action>");
					xmlBuff.append("<elementName><![CDATA[").append("").append("]]></elementName>");
					xmlBuff.append("<keyValue><![CDATA[").append("1").append("]]></keyValue>");
					xmlBuff.append("<taxKeyValue><![CDATA[").append("	").append("]]></taxKeyValue>");
					xmlBuff.append("<saveLevel><![CDATA[").append("1").append("]]></saveLevel>");
					xmlBuff.append("<forcedSave><![CDATA[").append(true).append("]]></forcedSave>");
					xmlBuff.append("<taxInFocus><![CDATA[").append(false).append("]]></taxInFocus>");
					xmlBuff.append("<description>").append("Header0 members").append("</description>");

					xmlBuff.append("<Detail1 objContext =\"1\"").append(" objName=\"receipt_adv\" domID=\"1\" dbID=\"\">");
					xmlBuff.append("<attribute selected=\"N\" updateFlag=\"A\" status=\"N\" pkNames=\"\"/>");
					xmlBuff.append("<tran_id/>");

					xmlBuff.append("<tran_date><![CDATA[" + tranDate + "]]></tran_date>");
					xmlBuff.append("<cust_code><![CDATA[" + custCode + "]]></cust_code>");
					xmlBuff.append("<tran_type><![CDATA[" + tranType + "]]></tran_type>");
					xmlBuff.append("<rcp_mode><![CDATA[" + rcpMode + "]]></rcp_mode>");
					xmlBuff.append("<bank_code><![CDATA[" + bankCode + "]]></bank_code>");
					xmlBuff.append("<ref_no><![CDATA[" + refNo + "]]></ref_no>");
					if (refDate != null)
					{
						xmlBuff.append("<ref_date><![CDATA[" + sdf.format(refDate) + "]]></ref_date>");
					} else
					{
						xmlBuff.append("<ref_date><![CDATA[]]></ref_date>");
					}
					xmlBuff.append("<site_code><![CDATA[" + siteCode + "]]></site_code>");

					xmlBuff.append("<confirmed><![CDATA[]]></confirmed>");
					xmlBuff.append("<auto_recd><![CDATA[]]></auto_recd>");
					xmlBuff.append("<adv_amt><![CDATA[").append("0").append("]]></adv_amt>");
					xmlBuff.append("<bill_amt><![CDATA[").append("0").append("]]></bill_amt>");
					if (effDate != null)
					{
						xmlBuff.append("<eff_date><![CDATA[" + sdf.format(effDate) + "]]></eff_date>");
					} else
					{
						xmlBuff.append("<eff_date><![CDATA[]]></eff_date>");
					}
					xmlBuff.append("<diff_amt__exch><![CDATA[]]></diff_amt__exch>");
					xmlBuff.append("<sale_order><![CDATA[]]></sale_order>");
					xmlBuff.append("<cust_bank_ref><![CDATA[]]></cust_bank_ref>");
					xmlBuff.append("<entry_batch_no><![CDATA[]]></entry_batch_no>");
					xmlBuff.append("<emp_code__aprv><![CDATA[]]></emp_code__aprv>");
					xmlBuff.append("<chq_amt><![CDATA[" + rcpAmt + "]]></chq_amt>");
					xmlBuff.append("<advadj_amt><![CDATA[").append("0").append("]]></advadj_amt>");
					xmlBuff.append("<fin_scheme><![CDATA[]]></fin_scheme>");
					xmlBuff.append("<item_ser><![CDATA[]]></item_ser>");
					xmlBuff.append("<rcp_type><![CDATA[]]></rcp_type>");
					xmlBuff.append("<remarks><![CDATA[" + remarks + "]]></remarks>");
					xmlBuff.append("<fin_entity><![CDATA[" + finEntity + "]]></fin_entity>");
					xmlBuff.append("</Detail1>");

					sql1 = " select ref_ser,ref_no,line_no__ref,rcp_amt from rcpdet_form where tran_id=? ";
					pstmt1 = conn.prepareStatement(sql1);
					pstmt1.setString(1, tranId);
					rs1 = pstmt1.executeQuery();
					while (rs1.next())
					{

						lineNo++;
						System.out.println("lineNo is " + lineNo);

						refSer = rs1.getString("ref_ser");
						refNo = rs1.getString("ref_no");
						lineNoRef = rs1.getString("line_no__ref");
						rcpAmtDet = rs1.getDouble("rcp_amt");

						refSer = refSer == null ? "" : refSer.trim();
						refNo = refNo == null ? "" : refNo.trim();
						lineNoRef = lineNoRef == null ? "" : lineNoRef.trim();

						xmlBuff.append("<Detail2 objContext=\"2\" objName=\"receipt_adv\" domID=\"1\" dbID=''>");
						xmlBuff.append("<attribute selected=\"N\" updateFlag=\"A\" status=\"N\" pkNames=\"\"/>");

						xmlBuff.append("<tran_id/>");
						xmlBuff.append("<line_no><![CDATA[" + lineNo + "]]></line_no>");
						xmlBuff.append("<line_no__ref><![CDATA[" + lineNoRef + "]]></line_no__ref>");
						xmlBuff.append("<ref_ser><![CDATA[" + refSer + "]]></ref_ser>");
						xmlBuff.append("<ref_no><![CDATA[" + refNo + "]]></ref_no>");
						xmlBuff.append("<rcp_amt><![CDATA[" + rcpAmtDet + "]]></rcp_amt>");
						xmlBuff.append("</Detail2>");
					}
					rs1.close();
					rs1 = null;
					pstmt1.close();
					pstmt1 = null;
					xmlBuff.append(advBuff.toString());

					xmlBuff.append("</Header0>");
					xmlBuff.append("</group0>");
					xmlBuff.append("</DocumentRoot>");
					xmlString = xmlBuff.toString();
					System.out.println("xmlString    " + xmlString);
					errString = saveData(siteCode, xmlString, conn);
					System.out.println("Passed xml in  master State full  errString   " + errString);

					if (errString.indexOf("Success") > -1)
					{

						String[] arrayForTranId = errString.split("<TranID>");
						int endIndex = arrayForTranId[1].indexOf("</TranID>");
						System.out.println("***********going for confirmation************");
						String tranIdForIssue = arrayForTranId[1].substring(0, endIndex);
						System.out.println("tranIdForIssue" + tranIdForIssue);
						errString = ReceiptAdv.confirm(tranIdForIssue, xtraParams, "", conn);

						System.out.println("=====Its Confirmed=====");
						System.out.println("retString from conf ::" + errString);
						if (errString.indexOf("VTCICONF3") > -1)
						{
							sql1 = " update receipt_form set status= 'P' where tran_id = ? ";
							pstmt1 = conn.prepareStatement(sql1);
							pstmt1.setString(1, tranId);
							cnt = pstmt1.executeUpdate();
							if (cnt > 0)
							{
								System.out.println("UPDATE QUERY FOR STATUS");
								conn.commit();
							}
							pstmt1.close();
							pstmt1 = null;
						} else
						{
							System.out.println("connection roll back for confirmation");
							conn.rollback();
						}
					} else
					{
						System.out.println("connection roll back for save data");
						conn.rollback();
					}
					System.out.println("Passed xml in  master State full  errString   " + errString);
				} else
				{
					sql1 = " update receipt_form set remarks = 'Mismatch amount in bank statement and total receipt amount',status= 'R' where tran_id = ? ";
					pstmt1 = conn.prepareStatement(sql1);
					pstmt1.setString(1, tranId);
					cnt = pstmt1.executeUpdate();
					if (cnt > 0)
					{
						conn.commit();
					}
					pstmt1.close();
					pstmt1 = null;
				}

			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;

		}
		catch(SQLException se)
		{
			isError = true;
			System.out.println("Exception : insReceipt : EcollectionSchedule" +se.getMessage());
			try
			{
				conn.rollback();
			}
			catch(Exception se1){}
			throw new ITMException(se);
		}finally
		{
				if(conn != null)
				{
					if(pstmt!=null)
					{
						pstmt.close();
						pstmt=null;
					}
					
					if(rs!=null)
					{
						rs.close();
						rs=null;
					}
				
					conn.close();
					conn= null;
				}
		}
	
		
		System.out.println("errString........:: " + errString);
		return errString;  	
	}
	
	private String saveData(String siteCode,String xmlString, Connection conn) throws ITMException
	{
		System.out.println("saving data...........");
		InitialContext ctx = null;
		String retString = null;
		MasterStatefulLocal masterStateful = null; // for ejb3
		try
		{
			AppConnectParm appConnect = new AppConnectParm();
			ctx = new InitialContext(appConnect.getProperty());
			masterStateful = (MasterStatefulLocal)ctx.lookup("ibase/MasterStatefulEJB/local");
			System.out.println("-----------masterStateful------- " + masterStateful);
			String [] authencate = new String[2];
			authencate[0] = "";
			authencate[1] = "";
			System.out.println("xmlString to masterstateful [" + xmlString + "]");
			retString = masterStateful.processRequest(authencate, siteCode, true, xmlString,true,conn);
		}
		catch(ITMException itme)
		{
			System.out.println("ITMException :CreateDistOrder :saveData :==>");
			throw itme;
		}
		catch(Exception e)
		{
			e.printStackTrace();
			System.out.println("Exception :CreateDistOrder :saveData :==>");
			throw new ITMException(e);
		}
		return retString;
	}	
	
	
	

}