/**
 * @author : Mahendra Jadhav 
 * @Request Id :F14ISUN011
 * Date : 02/02/15
 */
package ibase.webitm.ejb.fin.adv;

import ibase.system.config.AppConnectParm;
import ibase.system.config.ConnDriver;
import ibase.utility.CommonConstants;
import ibase.utility.E12GenericUtility;
import ibase.webitm.ejb.ActionHandlerEJB;
import ibase.webitm.ejb.ITMDBAccessEJB;
import ibase.webitm.ejb.MasterStatefulLocal;
import ibase.webitm.ejb.ValidatorEJB;
//import ibase.webitm.ejb.dis.DistCommon;
import ibase.webitm.ejb.fin.FinCommon;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;
import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.text.*;




import javax.ejb.Stateless;
import javax.naming.InitialContext;
@Stateless
public class GenReceiptConf extends ActionHandlerEJB implements GenReceiptConfLocal,GenReceiptConfRemote 
{
	
	E12GenericUtility e12GenericUtility = new E12GenericUtility();
	protected InitialContext ctx = null;
	
	
	public String confirm(String tranID,String xtraParams, String forcedFlag) throws RemoteException,ITMException
	{
		String retString = "";
		boolean isConn= false;
		Connection conn = null;
		

		try
		{
			retString = confirm( tranID, xtraParams, forcedFlag, conn );

			if ( retString != null && retString.length() > 0 )
			{
				throw new Exception("Exception while calling confirm for tran  Id:["+tranID+"]");
			}
		}
		catch(Exception exception)
		{
			System.out.println("Exception in [GenReceiptConf]: " + exception.getMessage());
		}
		return retString;
	}
	
	public String confirm(String tranId,String xtraParams,String forcedFlag, Connection conn) throws RemoteException,ITMException
	{
		System.out.println("confirm called.......");
		String sql = "",confirm="",siteCode="",errString="",userId="",tranSer = "",loginEmpCode="";
		String chgUser="",errStr="",returnString="";
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		FinCommon finCommon = null;
		GenericUtility genericUtility = null;
		ITMDBAccessEJB itmDBAccessEJB = null;
		ValidatorEJB validatorEJB = null;
		boolean connStatus=false;
		
		int cnt=0;
		try
		{
			System.out.println("Confirm method() :tran id = "+tranId);
			if ( conn == null )
			{
				ConnDriver connDriver = null;
				connDriver = new ConnDriver();
				conn = connDriver.getConnectDB("DriverITM");
				conn.setAutoCommit(false);
				connDriver = null;
				connStatus = true;
			}
			finCommon = new FinCommon();
			genericUtility = new GenericUtility();
			itmDBAccessEJB = new ITMDBAccessEJB();
			validatorEJB = new ValidatorEJB();
			userId =validatorEJB.getValueFromXTRA_PARAMS(xtraParams, "loginEmpCode");
			System.out.println("userId:"+userId);
			
			

			sql = "select confirmed ,site_code,chg_user from RECEIPT_FORM where tran_id = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,tranId);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				confirm = rs.getString("confirmed") == null ?"N":rs.getString("confirmed");
				siteCode = rs.getString("site_code") == null ?" ":rs.getString("site_code");
				chgUser = rs.getString("chg_user") == null ?" ":rs.getString("chg_user");
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;
			if(chgUser==null || chgUser.trim().length()==0)
			{
				chgUser="SYSTEM";
			}

			System.out.println("confirm  ::"+confirm);
			if(confirm != null  && confirm.equalsIgnoreCase("N"))
			{
				System.out.println("xtraParams["+xtraParams+"]");
				errString = generateReceipt(tranId,conn,xtraParams);
				System.out.println("err String from genReceiptConf ="+errString);
				
				if(errString.indexOf("Success") > -1)
				{
					
					
					sql="update receipt_form set confirmed='Y', conf_date = ? where tran_id= ?";
					pstmt = conn.prepareStatement( sql );	
					pstmt.setDate(1, new java.sql.Date(new java.util.Date().getTime()));
					pstmt.setString(2, tranId );
					cnt = pstmt.executeUpdate();					
					pstmt.close();
					pstmt = null;
					
					System.out.println("cnt==>"+cnt);
					if(cnt>0)
					{
						conn.commit();
						errStr = "VCNFSUC1";
						System.out.println("CONFIRMED SUCESSFULLY!!!!!!!");
						returnString = itmDBAccessEJB.getErrorString("",errStr,userId);
						return returnString;
					}
					
					
				}
				else
				{
					return errString;
					
				}
				
	
			}
			else
			{
				System.out.println("The Selected transaction is already confirmed");
				errString = itmDBAccessEJB.getErrorString("","VTMCONF1","","",conn);
				return errString;
			}
			System.out.println("115 err String from confirm method.....");
		} 
		catch( Exception e)
		{
			if(conn!=null)
			{
				try {
					conn.rollback();
				} catch (SQLException ex) {

					System.out.println("Exception : "+e);
					e.printStackTrace();
					throw new ITMException(e);

				}
			}
			System.out.println("Exception : "+e);
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			
				try
				{
					
					if(errString != null && errString.trim().length() > 0)
					{
						if( conn != null && !conn.isClosed() && connStatus ) 
						{
							if(errString.indexOf("VTCICONF3") > -1)
							{
								conn.commit();
							}
							else
							{
								conn.rollback();
							}
							conn.close();
							conn = null;
						}
					}
					if(rs != null)
					{
						rs.close();
						rs = null;
					}
					if(pstmt != null)
					{
						pstmt.close();
						pstmt = null;
					}
					//conn.close();
				}
				catch(Exception e)
				{
					System.out.println("Exception : "+e);e.printStackTrace();
					throw new ITMException(e);
				}
			
		}
		return errString;
	} //end of confirm method
	
	
	
	
	public String generateReceipt(String tranId,Connection conn, String xtraParams) throws Exception ,ITMException
	{
		ITMDBAccessEJB itmDBAccessEJB = null;
		String errString ="",xmlString="",sql="",acctCode="",remarks="",finEntity="";
		String lineNoRef="",refNo="",refSer="";
		String custCode="",tranType="",rcpMode="",bankCode="",custbankRef="",currCode="",currCodeHD="";
		String acctCodeArHD="",cctrCodeArHD="",acctCodeAdvHD="",cctrCodeAdvHD="";
		String acctCodeBalHD="",cctrCodeBalHD="",acctCodeCfHD="",cctrCodeCfHD="",acctCodeCfArHD="",cctrCodeCfArHD="",chgTerm="",chgUser="",loginEmpCode="";
		StringBuffer xmlBuff = new StringBuffer();
		StringBuffer advBuff = new StringBuffer();
		PreparedStatement pstmt=null;
		PreparedStatement pstmt1=null;
		ResultSet rs =null;
		ResultSet rs1 =null;
		
		String tranDate =null;
		int lineNo=0,lineNoCnt=0;
		String siteCode="";	
		HashMap<String, String> tempMap = new HashMap<String, String>();
		
		
		Date refDate=null,effDate=null,chgDate=null;
		double rcpAmt =0.0,chqAmt=0.0,totRcpAmt=0.0,adjAmt=0.0,chqAmtNew=0.0;
		
		itmDBAccessEJB = new ITMDBAccessEJB();
		SimpleDateFormat sdf = new SimpleDateFormat(e12GenericUtility.getApplDateFormat());
		try
		{
			
			
			SimpleDateFormat  simpleDateFormat = new SimpleDateFormat(e12GenericUtility.getApplDateFormat());
			java.util.Calendar cal = java.util.Calendar.getInstance();
			tranDate = simpleDateFormat.format(cal.getTime());
			
			chgUser = e12GenericUtility.getValueFromXTRA_PARAMS(xtraParams,"chgUser");
			chgTerm = e12GenericUtility.getValueFromXTRA_PARAMS(xtraParams,"chgTerm");
			loginEmpCode = e12GenericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginEmpCode"); 
			System.out.println("chgUser :"+chgUser);
			System.out.println("chgTerm :"+chgTerm);
			System.out.println("loginEmpCode :"+loginEmpCode);
			
			
            sql = "select CUST_CODE,TRAN_TYPE,RCP_MODE,BANK_CODE ,REF_NO,REF_DATE,SITE_CODE, " +
            		" EFF_DATE,CUST_BANK_REF,CHQ_AMT,REMARKS from RECEIPT_FORM where tran_id = ? ";
 
			
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, tranId);
			rs = pstmt.executeQuery();
			if (rs.next())
			{
				custCode=rs.getString("CUST_CODE");
				tranType=rs.getString("TRAN_TYPE");
				rcpMode=rs.getString("RCP_MODE");
				bankCode=rs.getString("BANK_CODE");
				refNo=rs.getString("REF_NO");
				refDate=rs.getDate("REF_DATE");
				siteCode=rs.getString("SITE_CODE");
				effDate=rs.getDate("EFF_DATE");
				custbankRef=rs.getString("CUST_BANK_REF");
				chqAmt=rs.getDouble("CHQ_AMT");
				remarks=rs.getString("REMARKS");
				
			
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;
			
			System.out.println("refDate :"+refDate);
			System.out.println("effDate :"+effDate);
			//System.out.println("refDate :"+refDate);
			
			custCode = custCode == null ? "" : custCode.trim();
			tranType = tranType == null ? "" : tranType.trim();
			rcpMode = rcpMode == null ? "" : rcpMode.trim();
			bankCode = bankCode == null ? "" : bankCode.trim();
			refNo = refNo == null ? "" : refNo.trim();
			siteCode = siteCode == null ? "" : siteCode.trim();
			custbankRef = custbankRef == null ? "" : custbankRef.trim();
			remarks = remarks == null ? "" : remarks.trim();
			chgUser = chgUser == null ? "" : chgUser.trim();
			chgTerm = chgTerm == null ? "" : chgTerm.trim();
			
			if(remarks == "")
			{
				remarks="auto generated receipt through domestic receipt-"+tranId;
			}
				
			/*---------------------------------------------------------------------------------------*/
			
				currCodeHD = currCodeHD == null ? "" : currCodeHD.trim();
				acctCodeArHD = acctCodeArHD == null ? "" : acctCodeArHD.trim();
				cctrCodeArHD = cctrCodeArHD == null ? "" : cctrCodeArHD.trim();
				acctCodeAdvHD = acctCodeAdvHD == null ? "" : acctCodeAdvHD.trim();
				cctrCodeAdvHD = cctrCodeAdvHD == null ? "" : cctrCodeAdvHD.trim();
				
				acctCodeBalHD = acctCodeBalHD == null ? "" : acctCodeBalHD.trim();
				cctrCodeBalHD = cctrCodeBalHD == null ? "" : cctrCodeBalHD.trim();
				acctCodeCfHD = acctCodeCfHD == null ? "" : acctCodeCfHD.trim();
				cctrCodeCfHD = cctrCodeCfHD == null ? "" : cctrCodeCfHD.trim();
				acctCodeCfArHD = acctCodeCfArHD == null ? "" : acctCodeCfArHD.trim();
				cctrCodeCfArHD = cctrCodeCfArHD == null ? "" : cctrCodeCfArHD.trim();
				
				System.out.println("currCodeHD :"+currCodeHD);
				System.out.println("acctCodeArHD :"+acctCodeArHD+"@cctrCodeArHD"+cctrCodeArHD);
				System.out.println("acctCodeAdvHD :"+acctCodeAdvHD+"@cctrCodeAdvHD"+cctrCodeAdvHD);
				
				System.out.println("acctCodeBalHD :"+acctCodeBalHD+"@cctrCodeBalHD"+cctrCodeBalHD);
				System.out.println("acctCodeCfHD :"+acctCodeCfHD+"@cctrCodeCfHD"+cctrCodeCfHD);
				System.out.println("acctCodeCfArHD :"+acctCodeCfArHD+"@cctrCodeCfArHD"+cctrCodeCfArHD);
				
				
				 sql = " select fin_entity from site where site_code=? " ;
		        	pstmt = conn.prepareStatement(sql);
					pstmt.setString(1,siteCode);
					rs = pstmt.executeQuery();
					if (rs.next())
					{
						finEntity=rs.getString("fin_entity");
					}
					rs.close();
					rs = null;
					pstmt.close();
					pstmt = null;
				
					finEntity = finEntity == null ? "" : finEntity.trim();
			
			/*------------------------changes done on 10-MARCH-2015------------------------------------*/
			
					sql=" select ref_ser,ref_no,line_no__ref,line_no,rcp_amt from rcpdet_form where tran_id=? ";
					System.out.println("<!@#>Adding detail 2.......... sql "+sql);
					pstmt1=conn.prepareStatement(sql);
					pstmt1.setString(1,tranId);
					rs1=pstmt1.executeQuery();

					while(rs1.next())
					{

						    lineNoCnt++;
						    System.out.println("lineNo is " + lineNoCnt);
					
						    refSer=rs1.getString("ref_ser");
						    lineNo=rs1.getInt("line_no");
						    refNo=rs1.getString("ref_no");
						    lineNoRef=rs1.getString("line_no__ref");
						    rcpAmt=rs1.getDouble("rcp_amt");
					        	    
						    
						    refSer = refSer == null ? "" : refSer.trim();
						    refNo = refNo == null ? "" : refNo.trim();
						    lineNoRef = lineNoRef == null ? "" : lineNoRef.trim();
						    System.out.println("lineNo :"+lineNo);
						   
						    totRcpAmt = totRcpAmt + rcpAmt;
						    
						    tempMap.put("line_no" + lineNoCnt, String.valueOf(lineNo));
						    tempMap.put("line_no_ref" + lineNoCnt, lineNoRef);
						    tempMap.put("ref_ser" + lineNoCnt, refSer);
						    tempMap.put("ref_no" + lineNoCnt, refNo);
						    tempMap.put("rcp_amt" + lineNoCnt, String.valueOf(rcpAmt));
						    
						    
						    
					}
					rs1.close();
					rs1=null;
					pstmt1.close();
					pstmt1=null;
					
			System.out.println("totRcpAmt :"+totRcpAmt);
			
		
			
/*--------------------------------------------------------------------------------------------------*/			

			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("<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>");//cheque 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>");
			
			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>");
			
			if(chqAmt > totRcpAmt)
			{
				adjAmt=chqAmt - totRcpAmt;
				
				xmlBuff.append("<chq_amt><![CDATA["+chqAmt+"]]></chq_amt>");
				xmlBuff.append("<adv_amt><![CDATA["+adjAmt+"]]></adv_amt>");
			}
			else
			{
				xmlBuff.append("<chq_amt><![CDATA["+chqAmt+"]]></chq_amt>");
				xmlBuff.append("<adv_amt><![CDATA[0]]></adv_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("<chg_user><![CDATA["+chgUser+"]]></chg_user>");
			xmlBuff.append("<chg_term><![CDATA["+chgTerm+"]]></chg_term>");
			xmlBuff.append("<chg_date><![CDATA["+tranDate+"]]></chg_date>");
			
			xmlBuff.append("</Detail1>");
			 
			
			System.out.println("rcpAmt :"+rcpAmt);
			System.out.println("lineNoCnt :"+lineNoCnt);
			
			for(int i = 1 ; i <= lineNoCnt ; i++ )
			{
					
					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["+tempMap.get("line_no" + i)+"]]></line_no>");
					xmlBuff.append("<line_no__ref><![CDATA["+tempMap.get("line_no_ref" + i)+"]]></line_no__ref>");
					xmlBuff.append("<ref_ser><![CDATA["+tempMap.get("ref_ser" + i)+"]]></ref_ser>");
					xmlBuff.append("<ref_no><![CDATA["+tempMap.get("ref_no" + i)+"]]></ref_no>");
					xmlBuff.append("<rcp_amt><![CDATA["+tempMap.get("rcp_amt" + i)+"]]></rcp_amt>");
					xmlBuff.append("</Detail2>");
			} 
			
			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,xtraParams,conn);

			System.out.println("Passed xml in  master State full  errString   " + errString);


		} catch(Exception e)
		{
			conn.rollback();
			e.printStackTrace();
			throw new ITMException(e);
			
		}

		return errString;
	}


	private String saveData(String siteCode,String xmlString,String xtraParams, Connection conn) throws ITMException
	{
		System.out.println("saving data...........");
		InitialContext ctx = null;
		String retString = null;
		MasterStatefulLocal masterStateful = null; // for ejb3
		ibase.utility.UserInfoBean userInfo;
		String chgUser="",chgTerm="";
		try
		{
			System.out.println("saveData@@@@@@");
			userInfo = new ibase.utility.UserInfoBean();
			chgUser = e12GenericUtility.getValueFromXTRA_PARAMS(xtraParams,"chgUser");
			chgTerm = e12GenericUtility.getValueFromXTRA_PARAMS(xtraParams,"chgTerm");
			userInfo.setLoginCode(chgUser);
			userInfo.setRemoteHost(chgTerm);
			System.out.println("chgUser :"+chgUser);
			System.out.println("chgTerm :"+chgTerm);
			
			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);
			retString = masterStateful.processRequest(userInfo,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;
	}	



}
