package ibase.webitm.ejb.fin;
import java.sql.*;
import org.w3c.dom.*;
import ibase.webitm.ejb.*;
import ibase.webitm.utility.GenericUtility;
import ibase.utility.CommonConstants;
import java.text.SimpleDateFormat;
import java.text.NumberFormat;
import java.text.DecimalFormat;
import ibase.webitm.utility.*;
import ibase.system.config.*;
import java.util.*;
public class InsuranceUpdate 
{

	transient GenericUtility genericUtility = null;
	ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
	public String gf_ins_upd(HashMap insUpdHMap,double netAmt,Connection conn) throws ITMException
	{
		genericUtility = GenericUtility.getInstance();   
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = "",errString ="";
		String tranIdIns="",currCode="",bulk="",docType="",docNo=""	,refSer="",certNo="",status="";
		String refId="";
		double docValue=0,exchRate=0; 
		double coverPerc=0,utilisedValue=0,allocValue=0,policyValue=0,premiumBulk=0,premiumCont=0,minLimit=0; 
		double updtrnd=0,ld_ins_value__fx=0,ld_prem=0,ld_orig=0,ld_prem_fx=0,ld_updutilprem=0;
		String ls_certno="",ls_old_doc_type="";
		double  ld_old_ins_value=0,ld_old_premium_value=0,ld_opening_ins_val = 0,ld_closing_ins_val =0;
		int upd =0,cnt =0;
		long updamt=0,ld_new=0; 
		Timestamp tranDate =null;
		try
		{
			tranIdIns	= insUpdHMap.get( "tran_id__ins" ).toString();
			docValue	= Double.parseDouble(insUpdHMap.get("doc_value").toString());
			currCode	= insUpdHMap.get("curr_code").toString();
			exchRate	= Double.parseDouble(insUpdHMap.get("exch_rate").toString());
			tranDate    = (Timestamp)insUpdHMap.get("doc_date");
			bulk		= insUpdHMap.get("bulk").toString();
			docType		= insUpdHMap.get("doc_type").toString();
			docNo		= insUpdHMap.get("doc_no").toString();
			refSer		= insUpdHMap.get("ref_ser").toString();
			certNo		= insUpdHMap.get("cert_no").toString();
			//changed by msalam on 22/01/08 as cover_perc will come in insUpdHMap
			String coverPercStr = null;
			coverPercStr = insUpdHMap.get( "cover_perc" ).toString();
			System.out.println( "coverPerc String from comming insUpdHMap.....................:[" + coverPercStr + "]" );
			coverPerc = Double.parseDouble( coverPercStr.trim() );//insUpdHMap.get( "cover_perc" ).toString() );
			System.out.println( "coverPerc from comming insUpdHMap.....................:" + coverPerc );
			//End changed by msalam on 22/01/08 as cover_perc will come in insUpdHMap
			System.out.println("comming insUpdHMap.....................:"+insUpdHMap);
			
			sql = "select cover_perc,utilised_value,alloc_value,policy_value,status,  "
                  + " premium_bulk,premium_cont,min_limit "
                  + " FROM  insurance "
                  + " WHERE tran_id = '"+tranIdIns+"' "; 
				  
			System.out.println("sql :"+sql);
	     	pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
            if(rs.next())
            {	
				//changed by msalam on 22/01/08 as cover_perc will come in insUpdHMap
				//coverPerc=rs.getDouble("cover_perc");
				//End changed by msalam on 22/01/08 as cover_perc will come in insUpdHMap
				utilisedValue=rs.getDouble( "utilised_value" );
				allocValue=rs.getDouble( "alloc_value" );
				policyValue=rs.getDouble( "policy_value" );
				status=rs.getString( "status" );
				premiumBulk=rs.getDouble( "premium_bulk" );
				premiumCont=rs.getDouble( "premium_cont" );
				minLimit=rs.getDouble( "min_limit" );		 
			}		
			rs.close();
			rs =null;
			pstmt.close();
			pstmt =null;
			System.out.println("coverPerc.....................:"+coverPerc);
			System.out.println("utilisedValue.....................:"+utilisedValue);
			System.out.println("allocValue.....................:"+allocValue);
			System.out.println("policyValue.....................:"+policyValue);
			System.out.println("status.....................:"+status);
			System.out.println("premiumBulk.....................:"+premiumBulk);
			System.out.println("premiumCont.....................:"+premiumCont);
			System.out.println("minLimit.....................:"+minLimit);
			System.out.println("netAmt.....................:"+netAmt);
			//commented by msalam on 23/01/08 as not in server source
			/*
			if ( ( netAmt +	utilisedValue ) > policyValue )
			{
				System.out.println("((netAmt +	utilisedValue ) ......" +netAmt+utilisedValue);

				errString = itmDBAccessEJB.getErrorString("","VTUTIL","");
				return errString;
			}
			*/
			//End commented by msalam on 23/01/08 as not in server source
			if(status.equalsIgnoreCase("C") && status.equalsIgnoreCase("X")	)
			{
				errString = itmDBAccessEJB.getErrorString("","VTCX","");
				return errString;
			}
			else
			{	
				updamt = (long)(coverPerc * (docValue ))/100	 ;
				updtrnd = (coverPerc * (docValue ))/100	 ;
				System.out.println("updamt.....................:"+updamt);
				System.out.println("updtrnd.....................:"+updtrnd);

				ld_ins_value__fx	 = updamt	;
				
				//commednted by msalam on 23/01/08 as not in server source
				//updamt = (long)(updamt * exchRate) ;
				//end commented by msalam on 23/01/08
				updtrnd = ld_ins_value__fx * exchRate ;

				System.out.println("updamt.....................:"+updamt);
				System.out.println("updtrnd.....................:"+updtrnd);
				
				//added by msalam on 23/01/08 as in server source
				//to write function Ceiling
				updamt = ceiling( updtrnd );
				//end added by msalam on 23/01/08
				
				//Commented by msalam on 23/01/08 as in server source
				/*
				if ((updtrnd - updamt) >= 0.5 )
				{
					updamt = updamt + 1	 ;
				}
				*/
				//End Commented by msalam on 23/01/08 as in server source
				if(("Y").equalsIgnoreCase(bulk))
				{
					ld_prem = premiumBulk ;
				}
				else
				{
					ld_prem = premiumCont ;
				}

				ld_orig   =	ld_ins_value__fx * ld_prem;
				ld_new	 =	(long)(ld_ins_value__fx * ld_prem);
				System.out.println("ld_orig.....................:"+ld_orig);
				System.out.println("ld_new.....................:"+ld_new);
				//Commented by msalam on 23/01/08 as in server source
				/*				
				if (ld_orig - ld_new >= 0.1 )
				{
						ld_prem_fx = ld_new + 1	;
				}
				System.out.println("ld_prem_fx.....................:"+ld_prem_fx);
				*/
				//End Commented by msalam on 23/01/08 as in server source
				
				//added by msalam on 23/01/08 as in server source
				//ld_prem_fx = ld_ins_value__fx * ld_prem / 100;
				ld_prem_fx = ld_ins_value__fx * ld_prem;
				ld_prem_fx = ceiling( ld_prem_fx );	
				//end added by msalam on 23/01/08
				ld_updutilprem = (updamt * ld_prem)/100; //for case s_ins.doc_type = "I'

				if(("O").equalsIgnoreCase(docType))
				{
					if ((allocValue + updamt) > policyValue ) 
					{	
						errString = itmDBAccessEJB.getErrorString("","VTALLO","");
						return errString;
					}
				}
				else if (("I").equalsIgnoreCase(docType)) 
				{
					if ((utilisedValue + updamt) > policyValue )
					{
						errString = itmDBAccessEJB.getErrorString("","VTUTIL","");
						return errString;
					}
				}	
			}
			if( errString.trim().length() == 0 )
			{

				sql = "select ref_id,cert_no,ins_value__fx,premium_value,doc_type  "
                  + " FROM  insurance_det "
                  + " WHERE tran_id__ins = '"+tranIdIns+"' "
				  + " and	  ref_ser = '"+refSer+"'  "
				  + " and	  ref_id =  '"+docNo+"'  "
				  + " and	  status = 'O' ";                
				System.out.println("sql :"+sql);
				pstmt = conn.prepareStatement(sql);
				rs = pstmt.executeQuery();
				if(rs.next())
				{	
					 
					  refId = rs.getString("ref_id");
					  ls_certno = rs.getString("cert_no");
					  ld_old_ins_value = rs.getDouble("ins_value__fx");
					  ld_old_premium_value = rs.getDouble("premium_value");
					  ls_old_doc_type = rs.getString("doc_type");  
				}		
				rs.close();
				pstmt.close();
				System.out.println("refId........................ :"+refId);
				if (certNo.equalsIgnoreCase(ls_certno))
				{
					errString = itmDBAccessEJB.getErrorString("","VTDUPREC","");
					return errString;
				}
			}
			
			ld_opening_ins_val = policyValue - utilisedValue;
			ld_closing_ins_val = ld_opening_ins_val - updamt;

			// Two new columns op_ins_val and cl_ins_bal in insert sql below
			// Inserting into insurance detail table
			if (errString.trim().length() == 0 )
			{
				sql = "insert into insurance_det (tran_id__ins,ref_ser,ref_id,ref_date,doc_type,premium_perc,ins_value,chg_date,"
					  +"chg_user,chg_term,doc_value,curr_code,exch_rate,premium_value,cert_no,status,ins_value__fx,	op_ins_val, cl_ins_val) "
					  + "values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ";
						System.out.println("sql.................. :"+sql);
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1,tranIdIns);
						pstmt.setString(2,refSer);
						pstmt.setString(3,docNo);
						pstmt.setTimestamp(4,tranDate);
						pstmt.setString(5,docType);
						pstmt.setDouble(6,ld_prem);
						pstmt.setLong(7,updamt);	  
						pstmt.setTimestamp(8,new Timestamp(System.currentTimeMillis()));
						pstmt.setString(9,"SYSTEM");
						pstmt.setString(10,"SYSTEM");
						pstmt.setDouble(11,docValue);
						pstmt.setString(12,currCode);
						pstmt.setDouble(13,exchRate);
						pstmt.setDouble(14,ld_updutilprem);
						pstmt.setString(15,certNo);
						pstmt.setString(16,"O");
						pstmt.setDouble(17,ld_ins_value__fx);
						pstmt.setDouble(18,ld_opening_ins_val);
						pstmt.setDouble(19,ld_closing_ins_val);
						upd = pstmt.executeUpdate();
						if(upd == 1)
						{
							System.out.println("Record inserted into insurance_det ==:"+upd);
						}
				
				
			//Updating insurance table fields alloc_value or utilised value depending
			//on the doc_type.
				if(docType.equalsIgnoreCase("O"))
				{
						sql ="update insurance set alloc_value = alloc_value "+updamt+" "
							 +"where tran_id = '"+tranIdIns+"' " ;
						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;
				}
				else if(docType.equalsIgnoreCase("I"))
				{

					if (policyValue - (utilisedValue + updamt) < minLimit) 
					{
						 errString = itmDBAccessEJB.getErrorString("","VTMINBAL","");
						 return errString;
					}
					else 
					{
						sql ="update insurance  set utilised_value = utilised_value +"+updamt+", "
							 +" utilised_premium = utilised_premium +"+ld_updutilprem+" "
							 +"where tran_id = '"+tranIdIns+"' " ;
						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;
					}
				}
				//changed by msalam on 23/01/08 as in server source
				//sql ="update invoice  set ins_amt = "+ld_prem_fx+", "
				//	 +" exch_rate__ins =  "+ld_ins_value__fx+" "
				//	 +"where invoice_id = '"+refId+"' " ;	
				sql ="update invoice  set ins_amt = " + ld_prem_fx + ", "
					 +" exch_rate__ins =  " + ld_ins_value__fx + " "
					 +"where invoice_id = '" + docNo + "' " ;	

				System.out.println("sql.................. :"+sql);
				pstmt = conn.prepareStatement(sql);			
				cnt = pstmt.executeUpdate();
				System.out.println("recoed updates "+cnt);
				pstmt.close();
				pstmt =null;
			}
		}
		catch(SQLException se)
		{	
			errString = se.getMessage();
			throw new ITMException(se);
		}
		catch(Exception e)
		{	
			errString = e.getMessage();
			throw new ITMException(e);
		}
		finally
		{
			try{
					if(rs != null)
					{
						rs.close();
						rs = null;
					}
					if(pstmt != null)
					{
						pstmt.close();
						pstmt = null;
					}
				}
				catch(Exception e){}
		}
		System.out.println("errString.................. :"+errString);
		return errString;
	}
	public int ceiling( double dVal ){
		return ( (int)dVal + 1 );
	}
}




