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.ArrayList;
import javax.ejb.Stateless;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import ibase.system.config.ConnDriver;
import ibase.webitm.ejb.ValidatorEJB;
import ibase.utility.E12GenericUtility;
import ibase.webitm.utility.ITMException;

/**
 * This class is used to define rate of interest based on the scheme type
 * @author Sana Khan<br>
 * Date :  29.04.2016
 * CCF / Req ID : F16ASUN014
 *
 */
@Stateless
public class LoanSchemeIntRate extends ValidatorEJB implements LoanSchemeIntRateLocal , LoanSchemeIntRateRemote 
{
	public String wfValData() throws RemoteException,ITMException
	{
		return "";
	}

	public String wfValData( String xmlString, String xmlString1, String xmlString2, String objContext, String editFlag, String xtraParams )throws RemoteException , ITMException
	{
		Document dom = null;
		Document dom1 = null;
		Document dom2 = null;
		E12GenericUtility genericUtility = new E12GenericUtility();
		String errString = "";
		System.out.println( "LoanScheme:::wfValData:value of xmlString ["+xmlString+"]" );
		System.out.println( "LoanScheme:::wfValDatavalue of xmlString1 ["+xmlString1+"]" );
		System.out.println( "LoanScheme:::wfValDatavalue of xmlString2 ["+xmlString2+"]" );
		System.out.println( "LoanScheme:::wfValData:objContext ..:: ["+objContext+"]" );
		System.out.println( "LoanScheme:::wfValData:editFlag ..:: ["+editFlag+"]" );
		System.out.println( "LoanScheme:::wfValData:xtraparams ..:: ["+xtraParams+"]" );
		try
		{
			if( xmlString != null && xmlString.trim().length() != 0 )
			{
				dom = genericUtility.parseString( xmlString );
			}
	
			if( xmlString1 != null && xmlString1.trim().length() != 0 )
			{
				dom1 = genericUtility.parseString(xmlString1);
			}
	
			if( xmlString2 != null && xmlString2.trim().length() != 0 )
			{
				dom2 = genericUtility.parseString( xmlString2 );
			}
			errString = wfValData ( dom , dom1 , dom2 , objContext , editFlag , xtraParams );
			System.out.println( "LoanScheme:::wfValData:errString in wfValdata1 is " +errString );
		}
		catch(Exception e)
		{
			e.printStackTrace();
			throw new ITMException(e);
		}
		return errString;
	}

	public String wfValData( Document dom, Document dom1,Document dom2, String objContext, String editFlag, String xtraParams ) throws RemoteException,ITMException
	{
		NodeList parentNodeList = null;
		NodeList childNodeList = null;

		Node parentNode = null;
		Node childNode = null;

		StringBuffer errStringXml = new StringBuffer( "<?xml version=\"1.0\"?>\r\n<Root><Errors>" );

		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		int currentFormNo = 0 , childNodeListLength = 0 , ctr = 0;
		ArrayList <String> errList = new ArrayList <String>();
		ArrayList <String>errFields = new ArrayList <String>();

		String childNodeName = "" , childNodeValue = "";
		String userId = "" ,msgType = "" , errCode = "" , errFldName = "" , errString = "" , sql = "" ;
		String schemeType = "" , effFromStr = "" , validUptoStr = "" , intRateStr = "";
		int errListSize = 0 , slctCnt = 0, prvEffFromCnt = 0;
		float intRate = 0.0f;
		java.util.Date currEffFromDate = null, currValidUptoDate = null;
		Timestamp currEffFromTmstp = null;

		try
		{
			ConnDriver connDriver = new ConnDriver();
			conn = connDriver.getConnectDB( "DriverITM" );
			userId = getValueFromXTRA_PARAMS( xtraParams,"loginCode" ); 

			E12GenericUtility genericUtility = new E12GenericUtility();
			SimpleDateFormat sdf = new SimpleDateFormat( genericUtility.getApplDateFormat() );

			if( objContext != null && objContext.trim().length() > 0 )
			{
				currentFormNo = Integer.parseInt( objContext );
			}

			switch( currentFormNo )
			{
			case 1 :
			{
				parentNodeList = dom.getElementsByTagName( "Detail1" );
				parentNode = parentNodeList.item(0);
				childNodeList = parentNode.getChildNodes();
				childNodeListLength = childNodeList.getLength();
				for( ctr = 0 ; ctr < childNodeListLength ; ctr++ )
				{
					childNode = childNodeList.item(ctr);
					if( childNode.getNodeType() != Node.ELEMENT_NODE )
					{
						continue;
					}
					childNodeName = childNode.getNodeName();
					if( childNode.getFirstChild() != null )
					{
						childNodeValue = childNode.getFirstChild().getNodeValue();
					}
					System.out.println( "LoanScheme:::wfValData:Child Node Value is"+childNodeValue );
					if( "scheme_type".equalsIgnoreCase( childNodeName ) )
					{
						schemeType = checkNull( genericUtility.getColumnValue( "scheme_type", dom ) );
						if( schemeType.length() == 0 )
						{
							errList.add( "VTLOANSCH1" );
							errFields.add(childNodeName.toLowerCase());
							msgType = errorType( conn , "VTLOANSCH1" );
							if ( "E".equalsIgnoreCase(msgType) )
							{
								break;
							}
						}
					}

					else if( "eff_from".equalsIgnoreCase( childNodeName ) )
					{
						if( "A".equalsIgnoreCase( editFlag ) )
						{
							effFromStr = checkNull( genericUtility.getColumnValue("eff_from", dom) );
							schemeType = checkNull( genericUtility.getColumnValue("scheme_type", dom) );
							if( effFromStr.length() > 0 )
							{
								try
								{
									currEffFromDate = sdf.parse( effFromStr );
									currEffFromTmstp = java.sql.Timestamp.valueOf( genericUtility.getValidDateTimeString( effFromStr, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat() ) );
								}
								catch( Exception e )
								{
									errList.add( "VTLOANSCH8" );
									errFields.add( childNodeName.toLowerCase() );
									msgType = errorType( conn , "VTLOANSCH8" );
									if ( "E".equalsIgnoreCase(msgType) )
									{
										break;
									}
								}
								
								sql = "SELECT COUNT(*) AS DUPCOUNT FROM LOANSCHEME_INT_RATE WHERE SCHEME_TYPE = ? AND EFF_FROM = ? ";
								pstmt = conn.prepareStatement( sql );
								pstmt.setString( 1, schemeType );
								pstmt.setTimestamp( 2, currEffFromTmstp );
								rs = pstmt.executeQuery();
								if( rs.next() )
								{
									slctCnt =  rs.getInt("DUPCOUNT");
								}
								close( pstmt , rs );
								if( slctCnt > 0 )
								{
									errList.add( "VTLOANSCH9" );
									errFields.add( childNodeName.toLowerCase() );
									msgType = errorType( conn , "VTLOANSCH9" );
									if ( "E".equalsIgnoreCase(msgType) )
									{
										break;
									}
								}

								sql = "";
								sql = "SELECT COUNT(*) AS PRV_EFF_FROM FROM LOANSCHEME_INT_RATE WHERE SCHEME_TYPE = ? AND EFF_FROM > ? ";
								pstmt = conn.prepareStatement( sql );
								pstmt.setString( 1, schemeType );
								pstmt.setTimestamp( 2, currEffFromTmstp );
								rs = pstmt.executeQuery();
								if( rs.next() )
								{
									prvEffFromCnt =  rs.getInt("PRV_EFF_FROM");
								}
								close( pstmt, rs );
								if( prvEffFromCnt > 0 )
								{
										errList.add( "VTLOANSCH3" );
										errFields.add( childNodeName.toLowerCase() );
										msgType = errorType( conn , "VTLOANSCH7" );
										if ( "E".equalsIgnoreCase(msgType) )
										{
											break;
										}
								}
							}
							else
							{
								errList.add( "VTLOANSCH2" );
								errFields.add( childNodeName.toLowerCase() );
								msgType = errorType( conn , "VTLOANSCH2" );
								if ( "E".equalsIgnoreCase(msgType) )
								{
									break;
								}
							}
						}
					}

					else if( "valid_upto".equalsIgnoreCase( childNodeName ) )
					{
						if( "A".equalsIgnoreCase( editFlag ) )
						{
							validUptoStr = checkNull( genericUtility.getColumnValue("valid_upto", dom) );
							effFromStr = checkNull( genericUtility.getColumnValue("eff_from", dom) );
							if( validUptoStr.length() > 0 && effFromStr.length() > 0 )
							{
								try
								{
									currValidUptoDate = sdf.parse( validUptoStr );
									currEffFromDate = sdf.parse( effFromStr );
								}
								catch( Exception e ) 
								{
									errList.add( "VTLOANSCH8" );
									errFields.add( childNodeName.toLowerCase() );
									msgType = errorType( conn , "VTLOANSCH8" );
									if ( "E".equalsIgnoreCase(msgType) )
									{
										break;
									}
								}
								if( currEffFromDate.after( currValidUptoDate ) )
								{
									errList.add( "VTLOANSCH5" );
									errFields.add( childNodeName.toLowerCase() );
									msgType = errorType( conn , "VTLOANSCH5" );
									if ( "E".equalsIgnoreCase(msgType) )
									{
										break;
									}
								}
							}
							else
							{
								errList.add( "VTLOANSCH4" );
								errFields.add( childNodeName.toLowerCase() );
								msgType = errorType( conn , "VTLOANSCH4" );
								if ( "E".equalsIgnoreCase(msgType) )
								{
									break;
								}
							}
						}
					}

					else if( "int_rate".equalsIgnoreCase( childNodeName ) )
					{
						intRateStr = checkNull( genericUtility.getColumnValue("int_rate", dom) );
						if( intRateStr.length() > 0 )
						{
							try
							{
								intRate = Float.parseFloat( intRateStr );
							}
							catch( Exception e )
							{
								errList.add( "VTLOANSC10" );
								errFields.add( childNodeName.toLowerCase() );
								msgType = errorType( conn , "VTLOANSC10" );
								if ( "E".equalsIgnoreCase(msgType) )
								{
									break;
								}
							}
							if( intRate < 0 )
							{
								errList.add( "VTLOANSCH6" );
								errFields.add( childNodeName.toLowerCase() );
								msgType = errorType( conn , "VTLOANSCH6" );
								if ( "E".equalsIgnoreCase(msgType) )
								{
									break;
								}
							}
						}
						else
						{
							errList.add( "VTLOANSCH7" );
							errFields.add( childNodeName.toLowerCase() );
							msgType = errorType( conn , "VTLOANSCH7" );
							if ( "E".equalsIgnoreCase(msgType) )
							{
								break;
							}
						}
					}
				}
			}
			break;
			}
			if( errList != null )
			{
				errListSize = errList.size();
			}
			System.out.println( "LoanScheme:::wfValData:errListSize:::::::["+errListSize+"]" );
			if ( errListSize > 0 )
			{
				for ( int i = 0; i < errListSize; i++ )
				{
					System.out.println("LoanScheme:::wfValData:errListSize::::::::in error For:::::::::::::::"); 
					errCode = (String) errList.get(i);
					errFldName = (String) errFields.get(i);
					System.out.println("LoanScheme:::wfValData:errListSize:::::::errCode .........."+errCode);					
					errString = getErrorString( errFldName, errCode, userId );
					System.out.println("LoanScheme:::wfValData:errListSize:::::::errString is : ::::>>>> " + errString);
					msgType =  errorType( conn , errCode );
					if ( errString.length() > 0 )
					{
						String bifurErrString = errString.substring( errString.indexOf("<Errors>") + 8,errString.indexOf("<trace>") );
						bifurErrString =bifurErrString+errString.substring( errString.indexOf("</trace>") + 8,errString.indexOf("</Errors>") );
						errStringXml.append( bifurErrString );
						System.out.println("LoanScheme:::wfValData:errListSize:::::::errStringXml .........."+errStringXml);
						errString = "";
					}
					if ( "E".equalsIgnoreCase(msgType) )
					{
						break;
					}
				}
				errList.clear();
				errList = null;
				errFields.clear();
				errFields = null;				
				errStringXml.append( "</Errors></Root>\r\n" );
			}
			else
			{
				errStringXml = new StringBuffer( "" );
			}
			errString = errStringXml.toString();
		}
		catch( Exception e )
		{
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally 
		{
			try 
			{
				close( pstmt, rs );
				if ( conn != null )
				{
					conn.close();
					conn = null;
				}
			} 
			catch ( Exception e )
			{
				e.printStackTrace();				
			}
		}
		return errString;
	}

	public String itemChanged( String xmlString, String xmlString1, String xmlString2, String objContext, String currentColumn, String editFlag, String xtraParams ) throws RemoteException, ITMException
	{
		Document dom = null;
		Document dom1 = null;
		Document dom2 = null;
		String errString = null;
		E12GenericUtility genericUtility = new E12GenericUtility();
		try
		{
			System.out.println( "LoanScheme:::itemChanged:::value of xmlString ["+xmlString+"]" );
			System.out.println( "LoanScheme:itemChanged:::value of xmlString ["+xmlString1+"]" );
			System.out.println( "LoanScheme:itemChanged:::value of xmlString ["+xmlString2+"]" );
			System.out.println( "LoanScheme:::itemChanged:::objContext ..:: ["+objContext+"]" );
			System.out.println( "LoanScheme:::itemChanged:::currentColumn ..:: ["+currentColumn+"]" );
			System.out.println( "LoanScheme:::itemChanged:::editFlag ..:: ["+editFlag+"]" );

			if ( xmlString != null && xmlString.trim().length() != 0 )
			{
				dom = genericUtility.parseString( xmlString ); 
			}
			if ( xmlString1 != null && xmlString1.trim().length() != 0 )
			{
				dom1 = genericUtility.parseString( xmlString1 ); 
			}
			if ( xmlString2 != null && xmlString2.trim().length() != 0 )
			{
				dom2 = genericUtility.parseString( xmlString2 ); 
			}
			errString = itemChanged( dom, dom1, dom2, objContext, currentColumn, editFlag, xtraParams );
			System.out.println ( "ErrString :" + errString );
		}
		catch ( Exception e )
		{
			System.out.println ( "Exception : LoanScheme :itemChanged(String,String):" + e.getMessage() + ":" );
			errString = genericUtility.createErrorString(e);
		}
		System.out.println ( "LoanScheme :itemChanged:::returning from itemChanged" );
		return errString;
	}

	public String itemChanged( Document dom, Document dom1, Document dom2, String objContext, String currentColumn, String editFlag, String xtraParams ) throws RemoteException, ITMException
	{
		int currentFormNo = 0;
		StringBuffer valueXmlString = null;
		String objNameDefault = "";
		String validUptoStr = "", sql = "", schemeType = "", schemeTypeDescr = "";
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		System.out.println( "LoanScheme:::itemChanged:::Value of edit Flag in itemchanged is :" + editFlag );

		if ( objContext != null && objContext.trim().length() > 0 )
		{
			currentFormNo = Integer.parseInt( objContext );
		}
		try
		{
			ConnDriver connDriver = new ConnDriver();
			conn = connDriver.getConnectDB( "Driver" );
			E12GenericUtility genericUtility =  new E12GenericUtility();		
			valueXmlString = new StringBuffer( "<?xml version=\"1.0\"?><Root><header><editFlag>" );
			valueXmlString.append(editFlag).append( "</editFlag></header>" );
			objNameDefault  = checkNull( getObjName( dom ,"1" ) );
			System.out.println( "LoanScheme:::itemChanged:::objNameDefault ..:: ["+objNameDefault+"]" );

			switch ( currentFormNo )
			{
			case 1:	
			{
				valueXmlString.append( "<Detail1 domID='1' dbID='' objContext='1' objName='"+objNameDefault+"' selected='Y'>\r\n" );
	
				if( "scheme_type".equalsIgnoreCase( currentColumn ) )
				{
					schemeType = checkNull( genericUtility.getColumnValue( "scheme_type", dom ) );
					sql = "SELECT DDF_GENCODE_DESC('SCHEME_TYPE','W_LOANSCHEME_INT_RATE',?, '') AS SCHEMETYPE_DESCR FROM DUAL";
					pstmt = conn.prepareStatement( sql );
					pstmt.setString( 1, schemeType );
					rs = pstmt.executeQuery();
					if( rs.next() )
					{
						schemeTypeDescr = checkNull( rs.getString( "SCHEMETYPE_DESCR" ) );
					}
					close( pstmt, rs );
					valueXmlString.append( "<scheme_type_descr>" ).append( "<![CDATA[" + schemeTypeDescr + "]]>" ).append( "</scheme_type_descr>" );
				}
				
				else if( "itm_defaultedit".equalsIgnoreCase( currentColumn )) 
				{
					validUptoStr = checkNull( genericUtility.getColumnValue( "valid_upto", dom) ); 
					System.out.println( "LoanScheme:::itemChanged:::Valid upto str is"+validUptoStr );
					valueXmlString.append( "<valid_upto protect ='1'>" ).append( validUptoStr ).append( "</valid_upto>" );
				}
				valueXmlString.append ( "</Detail1>\r\n" );
			}
			break;
			}
		}
		catch( Exception e )
		{
			throw new ITMException(e);
		}
		finally 
		{
			try 
			{
				close( pstmt, rs );
				if ( conn != null )
				{
					conn.close();
					conn = null;
				}
			} 
			catch ( Exception e )
			{
				e.printStackTrace();				
			}
		}
		valueXmlString.append( "</Root>\r\n" );
		System.out.println( "valueXmlString"+valueXmlString );
		return valueXmlString.toString();
	}

	/**
	 * This method is used to get node value of obj_name
	 * @param dom
	 * @param objContext
	 * @return objName
	 */
	private String getObjName( Document dom, String objContext )
	{
		Node elementName = null;
		NodeList elementList = null;
		String objName = "";
		elementList = dom.getElementsByTagName( "Detail"+objContext );
		elementName = elementList.item(0);

		if( elementName != null && ( "Detail"+objContext ).equalsIgnoreCase( elementName.getNodeName() ) )
		{
			NamedNodeMap etlAttributes = elementName.getAttributes();

			if( etlAttributes != null )
			{
				if( etlAttributes.getNamedItem( "obj_name" ) != null )
				{
					objName = etlAttributes.getNamedItem( "obj_name" ).getNodeValue();
				}
			}
		}
		return objName;
	}
	/**
	 * This method is used to return message type to the calling function
	 * @param conn
	 * @param errorCode
	 * @return msgType
	 * @throws ITMException
	 */
	private String errorType( Connection conn, String errorCode ) throws ITMException
	{
		String msgType = "";
		PreparedStatement pstmt = null ; 
		ResultSet rs = null;
		try
		{			
			String  sql = " SELECT MSG_TYPE FROM MESSAGES WHERE MSG_NO = ? ";
			pstmt = conn.prepareStatement( sql );			
			pstmt.setString(1, errorCode);			
			rs = pstmt.executeQuery();
			while( rs.next() )
			{
				msgType = rs.getString("MSG_TYPE");
			}	
			close( pstmt, rs );
		}
		catch ( Exception ex )
		{
			ex.printStackTrace();
			throw new ITMException(ex);
		}		
		finally
		{
			try
			{
				close( pstmt, rs );
			}
			catch ( Exception e )
			{
				e.printStackTrace();
				throw new ITMException(e);
			}
		}		
		return msgType;
	}

	/**
	 * 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();
		}
	}
}