package ibase.webitm.ejb.adm;
import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.ejb.Stateless;
import org.w3c.dom.Document;
import ibase.webitm.ejb.ValidatorEJB;
import ibase.utility.E12GenericUtility;
import ibase.webitm.utility.ITMException;

/**
 * This class is used to update loanscheme_int_rate table if
 * current valid upto date is less than existing valid upto date
 * @author Sana Khan<br>
 * Date : 29.04.2016
 *
 */
@Stateless
public class LoanSchemeIntRatePrs extends ValidatorEJB implements LoanSchemeIntRatePrsLocal , LoanSchemeIntRatePrsRemote 
{
	public String preSave()throws RemoteException,ITMException
	{
		return "";
	}
	public String preSave( String domString, String editFlag, String xtraParams, Connection conn ) throws RemoteException,ITMException
	{
		E12GenericUtility genericUtility =  new E12GenericUtility();

		Document dom = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;

		String sql = "" , effFromStr = "" , calEffFromStr = "" , schemeType = "" , userId = "" , errString = "";
		int validUptoDtCnt = 0 , updCnt = 0;
		java.util.Date effFromStrDate = null , calEffFromDate = null;
		Timestamp calEffFromTmstp = null , effFromTmstp = null;
		boolean errFound = false;


		try
		{
			if( domString != null && domString.trim().length() > 0 )
			{
				dom = genericUtility.parseString( domString );
			}
			System.out.println( "LoanSchemePrs:::preSave:Inside presave event" );
			SimpleDateFormat sdf = new SimpleDateFormat( genericUtility.getApplDateFormat() );
			userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginEmpCode");
			if( "A".equalsIgnoreCase( editFlag ) )
			{
				effFromStr = checkNull( genericUtility.getColumnValue("eff_from", dom) );
				schemeType = checkNull( genericUtility.getColumnValue("scheme_type", dom) );

				if( effFromStr.length() > 0 )
				{
					try
					{
						effFromStrDate = sdf.parse( effFromStr );
						effFromTmstp = java.sql.Timestamp.valueOf( genericUtility.getValidDateTimeString( effFromStr, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat() ) );
					}
					catch(Exception e)
					{
						errString = getErrorString("" , "VTLOANSCH8" , userId);
					}	
					sql = "SELECT COUNT(*) AS ROWCOUNT FROM LOANSCHEME_INT_RATE WHERE SCHEME_TYPE = ? AND ? BETWEEN EFF_FROM AND VALID_UPTO";
					pstmt = conn.prepareStatement( sql ) ;
					pstmt.setString( 1, schemeType );
					pstmt.setTimestamp( 2, effFromTmstp );
					rs = pstmt.executeQuery();
					if( rs.next() )
					{
						validUptoDtCnt = rs.getInt("ROWCOUNT");
					}
					close( pstmt, rs );

					if( validUptoDtCnt > 0 )
					{
						if( effFromStrDate != null )
						{
							calEffFromDate = subDays( effFromStrDate );
							try
							{
								calEffFromStr = sdf.format( calEffFromDate );
								calEffFromTmstp = java.sql.Timestamp.valueOf( genericUtility.getValidDateTimeString( calEffFromStr, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat() ) );
							}
							catch(Exception e)
							{
								errString = getErrorString("" , "VTLOANSCH8" , userId);
							}
							sql = "";
							sql = "UPDATE LOANSCHEME_INT_RATE SET VALID_UPTO = ? WHERE SCHEME_TYPE = ? AND ? BETWEEN EFF_FROM AND VALID_UPTO";
							pstmt = conn.prepareStatement(sql);
							pstmt.setTimestamp( 1, calEffFromTmstp );
							pstmt.setString( 2, schemeType );
							pstmt.setTimestamp( 3, effFromTmstp );
							updCnt = pstmt.executeUpdate();
							if(pstmt != null)
							{
								pstmt.close();
								pstmt = null;
							}
							System.out.println( "LoanSchemePrs:::preSave:::Update count is "+updCnt );
						}
					}
				}
			}
			else
			{
				System.out.println( "LoanSchemePrs:::preSave: returning from loanschemeprs as editflag is E" );
			}
		}
		catch( Exception e )
		{
			errFound = true;
			e.printStackTrace();
		}
		finally
		{
			try
			{	
				if( errFound == true )
				{
					conn.rollback();
				}
				else
				{
					conn.commit();
				}
				close( pstmt , rs );
			}
			catch ( Exception e )
			{
				System.out.println(e);
			}
		}
		return errString;
	}

	/** This method is used to subtract days
	 * @param effFromStrDate
	 * @return calEffFromDate
	 */
	private Date subDays( Date effFromStrDate )
	{
		Date calEffFromDate = null;
		try
		{
			Calendar cal = Calendar.getInstance();
			cal.setTime( effFromStrDate );
			cal.add( Calendar.DATE, -1 );
			calEffFromDate = cal.getTime();
			System.out.println( "LoanScheme:::subDays:::Returning effFrom date as "+calEffFromDate );
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return calEffFromDate;
	}
	/**
	 * This Method checks if value is equal to null or object is
	 * equal to null then set empty("") String.
	 * @param input
	 * @return String value 
	 */
	private String checkNull( String input )
	{
		if ( input == null || "null".equalsIgnoreCase(input) )
		{
			input= "";
		}
		return input.trim();
	}

	/**
	 * This method is used to close PreparedStatement and ResultSet
	 * @param pstmt
	 * @param rs
	 */
	private void close( PreparedStatement pstmt, ResultSet rs )
	{
		try
		{
			if ( rs != null )
			{
				rs.close();
				rs = null;
			}

			if( pstmt != null )
			{
				pstmt.close();
				pstmt = null;
			}
		}
		catch( Exception e )
		{
			e.printStackTrace();
		}
	}
}