package ibase.webitm.ejb.fin;
import ibase.webitm.utility.*;
import ibase.utility.CommonConstants;
import ibase.webitm.ejb.*;
import ibase.system.config.*;
import java.rmi.RemoteException;
import java.text.*;
import java.util.*;
import java.sql.*;
import org.w3c.dom.*;

import javax.xml.parsers.*;
import javax.ejb.*;
import javax.naming.InitialContext;
import java.io.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import ibase.webitm.ejb.fin.InsuranceUpdate;
import javax.ejb.Stateless; // added for ejb3
@Stateless // added for ejb3

public class InvInsurancePrc extends ProcessEJB implements InvInsurancePrcLocal,InvInsurancePrcRemote //SessionBean
{
	Connection conn = null;
	String errorString = null;
	GenericUtility genericUtility = GenericUtility.getInstance();
	ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
	
	/*public void ejbCreate() throws RemoteException, CreateException 
	{
		System.out.println("Create Method Called....");
	}
	public void ejbRemove()
	{
	}
	public void ejbActivate() 
	{
	}
	public void ejbPassivate() 
	{
	}*/
	public String process() throws RemoteException,ITMException
	{
		return "";
	}
	public String process(String xmlString, String xmlString2, String windowName, String xtraParams)
		throws RemoteException,ITMException
	{
		Document detailDom = null;
		Document headerDom = null;
		GenericUtility genericUtility = GenericUtility.getInstance();
		String retStr = "";
		try
		{				
			System.out.println("xmlString[process]::::::::::;;;"+xmlString);
			System.out.println("xmlString2[process]::::::::::;;;"+xmlString2);
			System.out.println("windowName[process]::::::::::;;;"+windowName);
			System.out.println("xtraParams[process]:::::::::;;;"+xtraParams);
		}
		catch(Exception e)
		{
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		try
		{	
			if(xmlString != null && xmlString.trim().length()!=0)
			{
				headerDom = genericUtility.parseString(xmlString); 
				System.out.println("headerDom" + headerDom);
			}
			if(xmlString2 != null && xmlString2.trim().length()!=0)
			{
				detailDom = genericUtility.parseString(xmlString2); 
				System.out.println("detailDom" + detailDom);
			}
			retStr = process(headerDom, detailDom, windowName, xtraParams);
		}
		catch (Exception e)
		{			
			System.out.println("Exception :InvInsurancePrcEJB :process(String xmlString, String xmlString2, String windowName, String xtraParams):" + e.getMessage() + ":");
			e.printStackTrace();
			retStr = e.getMessage();
		}
		return retStr;
	}//END OF PROCESS (1)

	public String process(Document headerDom, Document detailDom, String windowName, String xtraParams) throws RemoteException,ITMException
	{		
		String retStr = "";
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = "" ,sql1 = "",errString = "";
        String retString = "" ,errCode = "",tranId="";
		String loginSiteCode="",empCode="",chgUser="",chgTerm="",loginCode="";
		String 	policyNo="",insCertNo="",agent_code="",invoiceId="";
		String coverPerc = null;
		int count =0,cnt =0;
		String curr_code="";
	    double exch_rate=0,netAmt=0;
	    Timestamp tranDate =null;
		HashMap insUpdHMap = null;
		ConnDriver connDriver = new ConnDriver();
		//java.sql.Timestamp toDate =null;
		try
		{
			System.out.println("xtraParams :::::::::::::::::::::::::::::::::: "+xtraParams);
			loginSiteCode = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginSiteCode");
			empCode = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginEmpCode");
			chgUser = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"userId");
			chgTerm = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"termId");
			loginCode = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			System.out.println("empCode..............."+empCode);
			System.out.println("Login Site Code............."+loginSiteCode);
			System.out.println("userId............."+chgUser);
			System.out.println("termId............."+chgTerm);
			conn = connDriver.getConnectDB("DriverITM");
			conn.setAutoCommit(false);
			connDriver = null;
			policyNo  = genericUtility.getColumnValue( "policy_no", headerDom );
			insCertNo = genericUtility.getColumnValue( "ins_cert_no", headerDom );
			agent_code = genericUtility.getColumnValue( "agent_code", headerDom );
			invoiceId = genericUtility.getColumnValue( "invoice_id", headerDom );

			coverPerc = genericUtility.getColumnValue( "cover_perc", headerDom );
			
			System.out.println( "policyNo............." + policyNo );
			System.out.println( "agent_code............." + agent_code );
			System.out.println( "insCertNo............." + insCertNo );
			System.out.println( "invoiceId............." + invoiceId );
			System.out.println( "coverPerc............." + coverPerc );
			
			//vaildation of agent_code which was manually added by user
			if (agent_code == null || agent_code.trim().length() == 0 )
			{
				System.out.println("agent code is null..........");
				errString = itmDBAccessEJB.getErrorString("","VMAGTCD","");
				return errString;
			}
			else
			{
				sql =" select count(*) from ins_agent where agent_code = '"+agent_code+"' ";
				System.out.println("sql............."+sql);
				pstmt = conn.prepareStatement(sql);			
				rs = pstmt.executeQuery();
				if(rs.next())
				{
				   count = rs.getInt(1);
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;
				if(count == 0)
				{
					errString = itmDBAccessEJB.getErrorString("agent_code","VTIAC",loginCode);
					return errString;
				}
				else
				{
					// updating invoice for storing agent code for invoicewise reference for agent code
					sql ="update invoice set agent_code = '"+agent_code+"'  where invoice_id = '"+invoiceId+"' ";
					System.out.println("sql............."+sql);
					pstmt = conn.prepareStatement(sql);			
					cnt = pstmt.executeUpdate();
					if(cnt == 1)
					{
						System.out.println("recoed updates "+cnt);
					}
					pstmt.close();
					pstmt = null;
				}
			}
			if (invoiceId == null || invoiceId.trim().length() == 0 )
			{
				System.out.println("invoice id  is null..........");
				errString = itmDBAccessEJB.getErrorString("","VMINVCD1","");
				return errString;
			}
			else if (invoiceId != null || invoiceId.trim().length() != 0 )
			{
				sql =" select count(*) from invoice where invoice_id = '"+invoiceId+"' ";
				System.out.println("sql............."+sql);
				pstmt = conn.prepareStatement(sql);			
				rs = pstmt.executeQuery();
				if(rs.next())
				{
				   count = rs.getInt(1);
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;
				if(count == 0)
				{
					errString = itmDBAccessEJB.getErrorString("invoice_id","VTINVCD1",loginCode);
					return errString;
				}
				sql =" select count(*) from insurance_det where ref_id = '"+invoiceId+"' ";
				System.out.println("sql............."+sql);
				pstmt = conn.prepareStatement(sql);			
				rs = pstmt.executeQuery();
				if(rs.next())
				{
				   count = rs.getInt(1);
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;
				if(count > 0 )
				{
					errString = itmDBAccessEJB.getErrorString("invoice_id","VTALLRP",loginCode);
					return errString;
				}
				
			}	

			//validation for cover percentage [start]
			if( coverPerc == null || coverPerc.trim().length() == 0 )
			{
				System.out.println( "coverPerc is null.........." );
				errString = itmDBAccessEJB.getErrorString( "", "VMCVRPRC", "" );
				return errString;
			}
			else
			{
				sql =" select count( * ) from insurance "
					+" where POLICY_NO = '" + policyNo.trim() + "'" 
					+" 	 and COVER_PERC = " + coverPerc.trim() ;
				System.out.println("coverPerc validation sql............."+sql);
				pstmt = conn.prepareStatement( sql );			
				rs = pstmt.executeQuery();
				if( rs.next() )
				{
				   count = rs.getInt( 1 );
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;
				if( count == 0 )
				{
					//check for availability of cover percentage in insurance_cover table for that employee
					sql =" select count( * ) from insurance_cover c "
						+" where c.tran_id in (select tran_id from insurance "
						+"		     where POLICY_NO = '" + policyNo.trim() + "' ) "
						+"      and COVER_PERC = " + coverPerc.trim();
					System.out.println("coverPerc validation sql............."+sql);
					pstmt = conn.prepareStatement( sql );			
					rs = pstmt.executeQuery();
					if( rs.next() )
					{
					   count = rs.getInt( 1 );
					}
					rs.close();
					rs = null;
					pstmt.close();
					pstmt = null;
					//end check
					if( count == 0 )
					{
						errString = itmDBAccessEJB.getErrorString( "cover_perc", "VMINVCVPRC",loginCode);
						return errString;
					}
				}
			}
			//validation for cover percentage [end]
			//VALIDATION FOR CUSTORMER[start]
			//If there is customer defined for policy_no, then that must be in invoice
			sql =" SELECT COUNT( IC.CUST_CODE ) FROM "
				+"	INSURANCE I inner JOIN INSURANCE_CUST IC ON I.TRAN_ID = IC.TRAN_ID "
				+" WHERE I.POLICY_NO = '" + policyNo.trim() + "'";
				
			System.out.println( "CUSTORMER validation sql............." + sql );
			
			pstmt = conn.prepareStatement( sql );			
			rs = pstmt.executeQuery();
			if( rs.next() )
			{
			   count = rs.getInt( 1 );
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;
			if( count > 0 )
			{
				sql = "SELECT count(*) "
					+" FROM (SELECT CUST_CODE FROM INVOICE WHERE INVOICE_ID = '" + invoiceId.trim() + "') inv"
					+" where inv.cust_code in (SELECT IC.CUST_CODE FROM " 
					+" 			INSURANCE I inner JOIN INSURANCE_CUST IC ON I.TRAN_ID = IC.TRAN_ID "
					+" 		WHERE I.POLICY_NO = '" + policyNo.trim() + "')";
					
				System.out.println( "CUSTORMER validation sql............." + sql );
				
				pstmt = conn.prepareStatement( sql );			
				rs = pstmt.executeQuery();
				if( rs.next() )
				{
				   count = rs.getInt( 1 );
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;
				if( count == 0 )
				{
					errString = itmDBAccessEJB.getErrorString( "policy_no", "VMINVCUST",loginCode);
					return errString;
				}
			}
			//VALIDATION FOR CUSTORMER[end]
			//select tran_id into :ls_tran_id from insurance where policy_no = :ls_policy_no ;
			sql =" select tran_id from insurance where policy_no = '"+policyNo+"' ";
			System.out.println( "sql............." + sql);
			pstmt = conn.prepareStatement(sql);			
			rs = pstmt.executeQuery();
			if(rs.next())
			{
			   tranId = rs.getString("tran_id");
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;

			sql =" select curr_code,exch_rate,net_amt,tran_date from invoice where invoice_id = '"+invoiceId+"' ";
			System.out.println("sql............."+sql);
			pstmt = conn.prepareStatement(sql);			
			rs = pstmt.executeQuery();
			if(rs.next())
			{  
			   curr_code  = rs.getString("curr_code");
			   exch_rate  = rs.getDouble("exch_rate");
			   netAmt	  = rs.getDouble("net_amt");
			   tranDate   = rs.getTimestamp("tran_date");				  
			}
			System.out.println("curr_code............."+curr_code);
			System.out.println("exch_rate............."+exch_rate);
			System.out.println("netAmt............."+netAmt);
			System.out.println("tranDate............."+tranDate);
			rs.close();
			rs = null;
			pstmt.close();
			pstmt =null;

			if(netAmt ==0)
			{
				errString = itmDBAccessEJB.getErrorString("","VTNETZ","");
				return errString;
			}
			if(exch_rate == 0)
			{
				errString = itmDBAccessEJB.getErrorString("","VTEXCH1","");
				return errString;
			}
			if(curr_code == null)
			{
				errString = itmDBAccessEJB.getErrorString("","VTCURRCD1","");
				return errString;
			}
			if(tranId.trim().length() > 0)
			{
					insUpdHMap = new HashMap();
					insUpdHMap.put("tran_id__ins",tranId);
					insUpdHMap.put("doc_no",invoiceId);
					insUpdHMap.put("ref_ser","S-INV");
					insUpdHMap.put("doc_date",tranDate);
					insUpdHMap.put("doc_value",new Double(netAmt));
					insUpdHMap.put("curr_code",curr_code);
					insUpdHMap.put("exch_rate",new Double(exch_rate));
					insUpdHMap.put("doc_type","I");
					insUpdHMap.put("cert_no",insCertNo);
					insUpdHMap.put("bulk","Y");
					//Added by msalam on 22/01/08 as it was not considered before
					insUpdHMap.put( "cover_perc", coverPerc.trim() );
					//end added by msalam on 22/01/08
					sql =" select count(*) from insurance_det where tran_id__ins = '"+tranId+"' and "
						+" ref_ser = 'S-INV' and "
						+" ref_id =  ' " + invoiceId + " '  and"
						+" cert_no =  '" + insCertNo + "' ";
					pstmt = conn.prepareStatement(sql);
					System.out.println("sql............."+sql);
					rs = pstmt.executeQuery();
					if(rs.next())
					{
					   cnt = rs.getInt(1);
					}
					rs.close();
					pstmt.close();
					pstmt =null;
					if(cnt > 0 )
					{
						//errString = getErrorString("insurance_det","VTINSNF1",loginCode);
						errString = itmDBAccessEJB.getErrorString("insurance_det","VTINSNF1",loginCode);
					}
					else
					{
					   System.out.println("calling ....InsuranceUpdate");
					   InsuranceUpdate insuranceUpdate = new InsuranceUpdate();
					   errString = insuranceUpdate.gf_ins_upd(insUpdHMap,netAmt,conn);
					   System.out.println("errString .........."+errString);
					   if(errString.trim().length() > 1)
						{
						   return errString	;
						}
					}
				}
				else
				{
					errString = itmDBAccessEJB.getErrorString("","VTINSNF","");
					return errString;
				}
			}
	   	catch(Exception e)
		{
			   System.out.println("Exception in InvInsurancePrcEJB..."+e.getMessage());
			   e.printStackTrace();
			   errString = e.getMessage();

		}
		finally
		{
			try
			{		
				if(errString.trim().length() > 0)
				{
					conn.rollback();
					System.out.println(" Rollback connection.............");
					errString = itmDBAccessEJB.getErrorString("","VTPROUNSUC","");
				}
				else
				{
					conn.commit();
					System.out.println("commiting connection.............");
					errString = itmDBAccessEJB.getErrorString("","VTCONF","");
				}
				if (pstmt != null)
				{
					pstmt.close();
				}
				if(conn != null)
				{
					conn.close();
					conn = null;
				}	
			}
			catch(Exception e)
			{
			   System.out.println("Error In closing connection::==> "+e);
		       e.printStackTrace();
			}
		}
		System.out.println("returning from  InvInsurancePrcEJB   "+errString);
	    return (errString);
	}

}