package ibase.webitm.ejb.mfg;
import java.rmi.RemoteException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.ejb.SessionBean;
import javax.ejb.CreateException;
import ibase.webitm.utility.ITMException;
import ibase.webitm.utility.GenericUtility;
import ibase.system.config.ConnDriver;
import ibase.webitm.ejb.*;
import javax.ejb.Stateless; // added for ejb3

@Stateless // added for ejb3
public class BatchsizeAprvIC extends ValidatorEJB implements BatchsizeAprvICLocal,BatchsizeAprvICRemote
{
	GenericUtility genericUtility = GenericUtility.getInstance();
	String userId = null;
	String loginSite = null;
	

	/* public void ejbCreate() throws RemoteException, CreateException 
	{
		System.out.println("BatchsizeAprvICEJB is in Process..........");
	}
	public void ejbRemove()
	{
	}
	public void ejbActivate() 
	{
	}
	public void ejbPassivate() 
	{
	} */
	public String wfValData() throws RemoteException,ITMException
	{
		return "";
	}
	public String itemChanged() 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;
		String  errString = null;
		System.out.println("Validation Start..........");
		try
		{
			dom = parseString(xmlString);
			dom1 = parseString(xmlString1); 
			if (xmlString2.trim().length() > 0 )
			{
				dom2 = parseString(xmlString2);
			}
			errString = wfValData(dom,dom1,dom2,objContext,editFlag,xtraParams);
		}
		catch(Exception e)
		{
			System.out.println("Exception : BatchsizeAprvICEJB : wfValData(String xmlString) : ==>\n"+e.getMessage());
		}
		return (errString);
	}
	public String wfValData(Document dom, Document dom1,Document dom2, String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		String errString = " ";
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		int ctr = 0;
		String columnValue = null;
		String childNodeName = null;
		String errCode = null;

		int cnt = 0;
		int currentFormNo = 0;
		int childNodeListLength;
		Connection conn = null;
		PreparedStatement pstmt=null;
		ResultSet rs = null;
		String sql = null;
		ResultSet rs1 = null;
		String sql1 = null;
				
	    ConnDriver connDriver = new ConnDriver();
    	try
		{
			System.out.println( "wfValData called" );
			conn = connDriver.getConnectDB("DriverITM");
			userId = getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			loginSite = getValueFromXTRA_PARAMS(xtraParams, "loginSiteCode");
			genericUtility = GenericUtility.getInstance(); 
			if(objContext != null && objContext.trim().length()>0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}
			switch(currentFormNo)
			{
				case 1 :
					System.out.println("VALIDATION FOR DETAIL [ 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);
						childNodeName = childNode.getNodeName();
						
						if ( childNodeName.equalsIgnoreCase( "valid_upto" ) )
						{
							String effFromStr = null;
							String validUptoStr = null;

							errCode = null;
							
							validUptoStr = genericUtility.getColumnValue( "valid_upto", dom1 );									
							if(	validUptoStr == null || validUptoStr.trim().length() == 0  )
							{
								errCode = "VMVUTOBLK";
								errString = getErrorString( "valid_upto", errCode, userId );
							}
							effFromStr = genericUtility.getColumnValue( "eff_from", dom1 );
							if(	effFromStr == null || effFromStr.trim().length() == 0  )
							{
								errCode = "VMEFRMBLK";
								errString = getErrorString( "eff_from", errCode, userId );
							}
							
							if ( errCode == null )
							{		
								Timestamp effFrom = null;
								Timestamp validUpto = null;
							
								validUpto = Timestamp.valueOf(genericUtility.getValidDateString(validUptoStr, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat()) + " 00:00:00.0");

								effFrom = Timestamp.valueOf(genericUtility.getValidDateString(effFromStr, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat()) + " 00:00:00.0");
								
								if( validUpto.compareTo ( effFrom ) < 0 )
								{
									errCode = "EFFFROM";
								}
								if( errCode != null )
								{
									errString = getErrorString( "eff_from", errCode, userId );									
								}
							}
							if( errCode == null )
							{
								errCode = isValidPeriod( dom1, conn );
								if( errCode != null )
								{
									errString = getErrorString( "valid_upto", errCode, userId );
								}
							}
						}
						if ( childNodeName.equalsIgnoreCase( "site_code" ) )
						{
							String siteCode = null;
							siteCode = genericUtility.getColumnValue( "site_code", dom1 );
										
							if(	siteCode != null && siteCode.trim().length() > 0 )
							{
								sql = " SELECT COUNT(*) FROM site WHERE site_code ='" + siteCode.trim() + "'";
								System.out.println( " SQL FOR site_code ====> " + sql );
								pstmt = conn.prepareStatement( sql );
								rs = pstmt.executeQuery();
								cnt = 0;
								if( rs.next() )
								{
									cnt = rs.getInt( 1 );
								} 
								if( cnt == 0 )
								{
									errCode = "VMINVSITE";
									errString = getErrorString( "site_code", errCode, userId );
								}
								rs.close();
								rs = null;

								pstmt.close();
								pstmt = null;
							}
						}
						if ( childNodeName.equalsIgnoreCase( "site_code__mfg" ) )
						{
							String siteCodeMfh = null;
							siteCodeMfh = genericUtility.getColumnValue( "site_code__mfg", dom1 );
										
							if(	siteCodeMfh != null && siteCodeMfh.trim().length() > 0 )
							{
								sql = " SELECT COUNT(*) FROM site WHERE site_code ='" + siteCodeMfh.trim() + "'";
								System.out.println( " SQL FOR site_code__mfg ====> " + sql );
								pstmt = conn.prepareStatement( sql );
								rs = pstmt.executeQuery();
								cnt = 0;
								if( rs.next() )
								{
									cnt = rs.getInt( 1 );
								} 
								if( cnt == 0 )
								{
									errCode = "VMSTMFGINV";
									errString = getErrorString( "site_code__mfg", errCode, userId );
								}
								rs.close();
								rs = null;
								pstmt.close();
								pstmt = null;
							}
						}
						if ( childNodeName.equalsIgnoreCase( "item_code" ) )
						{
							String itemCode = null;
							itemCode = genericUtility.getColumnValue( "item_code", dom1 );
										
							if(	itemCode == null || itemCode.trim().length() == 0 )
							{
								errCode = "VMITEMBLK";
								errString = getErrorString( "item_code", errCode, userId );
							}
										
							if(	itemCode != null && itemCode.trim().length() > 0 )
							{
								sql = " SELECT COUNT(*) FROM item WHERE item_code ='" + itemCode.trim() + "'";
								System.out.println( " SQL FOR item_code ====> " + sql );
								pstmt = conn.prepareStatement( sql );
								rs = pstmt.executeQuery();
								cnt = 0;
								if( rs.next() )
								{
									cnt = rs.getInt( 1 );
								} 
								System.out.println(" COUNT =====> [" + cnt + "]");
								if( cnt == 0 )
								{
									errCode = "VMINVITEM";
									errString = getErrorString( "item_code", errCode, userId );
								}
								rs.close();
								rs = null;

								pstmt.close();
								pstmt = null;
							}
						}
						if ( childNodeName.equalsIgnoreCase ( "site_code" ) )
						{
							String siteCode = null;
							siteCode = genericUtility.getColumnValue( "site_code", dom1 );
										
							if(	siteCode == null || siteCode.trim().length() == 0 )
							{
								errCode = "VMSITEBLK";
								errString = getErrorString( "siteCode", errCode, userId );
							}
						} 
						if ( childNodeName.equalsIgnoreCase ( "site_code__mfg" ) )
						{
							String siteCodeMfg = null;
							siteCodeMfg = genericUtility.getColumnValue( "site_code__mfg", dom1 );
										
							if(	siteCodeMfg == null || siteCodeMfg.trim().length() == 0 )
							{
								errCode = "VMSTMFGBLK";
								errString = getErrorString( "siteCodeMfg", errCode, userId );
							}
						} 
						if ( childNodeName.equalsIgnoreCase ( "batch_size" ) )
						{
							String batchSize = null;
							batchSize = genericUtility.getColumnValue( "batch_size", dom1 );
										
							if(	batchSize == null || batchSize.trim().length() == 0 )
							{
								errCode = "VMBATCHBLK";
								errString = getErrorString( "batch_size", errCode, userId );
							}
						} 
						if ( childNodeName.equalsIgnoreCase ( "eff_from" ) )
						{
							String effFrom = null;
							effFrom = genericUtility.getColumnValue( "eff_from", dom1 );
							if(	effFrom == null || effFrom.trim().length() == 0  )
							{
								errCode = "VMEFRMBLK";
								errString = getErrorString( "eff_from", errCode, userId );
							}
						}
						//added by msalam on 010709 for add supplier validation with itemmnfr_det and then this
						if ( childNodeName.equalsIgnoreCase ( "supp_code__mfg" ) )
						{
							String itemCode = null;
							String suppCode = null;
							itemCode = genericUtility.getColumnValue( "item_code", dom1 );
							suppCode = genericUtility.getColumnValue( "supp_code__mfg", dom1 );
							if(	suppCode != null || suppCode.trim().length() > 0  )
							{
								
								sql = " SELECT COUNT(1) FROM itemmnfr_det WHERE item_code = ? and SUPP_CODE__MNFR = ? ";
								
								pstmt = conn.prepareStatement( sql );
								pstmt.setString( 1, itemCode );
								pstmt.setString( 2, suppCode );
								
								rs = pstmt.executeQuery();
								cnt = 0;
								if( rs.next() )
								{
									cnt = rs.getInt( 1 );
								} 
								rs.close();
								rs = null;

								pstmt.close();
								pstmt = null;
								
								if( cnt == 0 )
								{
									errCode = "VMINVSUPP";
									errString = getErrorString( "supp_code__mfg", errCode, userId );
								}
							}
						}						
						//end added by msalam on 010709 for add supplier validation with itemmnfr_det and then this
					} //END OF FOR LOOP OF CASE1
					break;
			}//END SWITCH 
		}//END TRY
		catch(Exception e)
		{
			System.out.println("Exception ::" +e);
			e.printStackTrace();
			errString = e.getMessage();
		}
		finally
		{
			try
			{
				if(conn != null)
				{
					if( pstmt != null )
					{
						pstmt.close();
						pstmt = null;
					}
					
					if( rs != null )
					{
						rs.close();
						rs = null;
					}
					conn.close();
				}
				conn = null;
			}
			catch(Exception d)
			{
			  d.printStackTrace();
			}			
			System.out.println(" < ExprProcessIcEJB > CONNECTION IS CLOSED");
		}
		System.out.println("ErrString ::" + errString);
		return errString;
	}//END OF VALIDATION 

	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 valueXmlString = null;
		try
		{
			dom = parseString(xmlString); 
			System.out.println("xmlString" + xmlString);
			dom1 = parseString(xmlString1); 
			System.out.println("xmlString1" + xmlString1);
			if (xmlString2.trim().length() > 0 )
			{
				System.out.println("xmlString2" + xmlString2);
				dom2 = parseString("<Root>" + xmlString2+ "</Root>");
			}
			valueXmlString = itemChanged(dom,dom1,dom2,objContext,currentColumn,editFlag,xtraParams);
		}
		catch(Exception e)
		{
			System.out.println("Exception : [BatchsizeAprvICEJB][itemChanged(String,String)] :==>\n"+e.getMessage());
		}
        return valueXmlString; 
	}
	public String itemChanged(Document dom, Document dom1,Document dom2, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		Connection conn = null;
		ConnDriver connDriver = new ConnDriver();
		PreparedStatement vPStmt = null;
		ResultSet vRs = null;
		String sql = null;
		int currentFormNo = 0;
		StringBuffer valueXmlString = new StringBuffer();
		String columnValue = null;
		NodeList parentNodeList = null;
		Node parentNode = null; 
		Node childNode = null;
		NodeList childNodeList = null;
		String childNodeName = null;
		int childNodeListLength = 0;
		int ctr = 0;
		String  loginSite = null; 
		
		try
		{
			conn = connDriver.getConnectDB("DriverITM");
			connDriver = null;
			if(objContext != null && objContext.trim().length()>0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}
			
			loginSite = getValueFromXTRA_PARAMS(xtraParams, "loginSiteCode");
			
			System.out.println("[BatchsizeAprvICEJB] [itemChanged] :currentFormNo ....." +currentFormNo);
			valueXmlString = new StringBuffer("<?xml version=\"1.0\"?><Root><header><editFlag>");
			valueXmlString.append(editFlag).append("</editFlag></header>");
			System.out.println("Current Form No ["+currentFormNo+"]");							
			switch (currentFormNo)
			{
				
				case 1:
					//SEARCHING THE DOM FOR THE INCOMING COLUMN VALUE START
					valueXmlString.append("<Detail1>");	
					parentNodeList = dom.getElementsByTagName("Detail1");
					parentNode = parentNodeList.item(0);
					childNodeList = parentNode.getChildNodes();
					ctr = 0;
					childNodeListLength = childNodeList.getLength();
					do
					{
						childNode = childNodeList.item(ctr);
						childNodeName = childNode.getNodeName();
						if(childNodeName.equals(currentColumn))
						{
							if (childNode.getFirstChild() != null)
							{
								columnValue=childNode.getFirstChild().getNodeValue().trim();
							}
						}
						ctr++;
					}while(ctr < childNodeListLength  && !childNodeName.equals(currentColumn));
					System.out.println("[" + currentColumn + "] ==> '" + columnValue + "'");
					if (currentColumn.trim().equals( "itm_default" ))
					{
						String vSql = null;
						String siteDescr = null;
						vSql = "select descr from site where site_code = '" + loginSite + "'";
						vPStmt = conn.prepareStatement( vSql );
						vRs = vPStmt.executeQuery();
						if( vRs.next() )
						{
							siteDescr = vRs.getString( "descr" );
						}
						vRs.close();
						vRs = null;
						vPStmt.close();
						vPStmt = null;
						
						valueXmlString.append("<site_code>").append("<![CDATA[" + ( loginSite != null ? loginSite.trim() : ""  )+ "]]>").append("</site_code>");
						valueXmlString.append("<site_code_descr>").append("<![CDATA[" + ( siteDescr != null ? siteDescr.trim() : ""  )+ "]]>").append("</site_code_descr>");
						valueXmlString.append("<tran_date>").append("<![CDATA[" + getCurrdateAppFormat() + "]]>").append("</tran_date>");
						valueXmlString.append("<eff_from>").append("<![CDATA[" + getCurrdateAppFormat() + "]]>").append("</eff_from>");
					}
					if (currentColumn.trim().equals( "site_code" ))
					{
						String vSql = null;
						String siteDescr = null;
						vSql = "select descr from site where site_code = '" + ( columnValue != null ? columnValue.trim() : "" ) + "'";
						vPStmt = conn.prepareStatement( vSql );
						vRs = vPStmt.executeQuery();
						if( vRs.next() )
						{
							siteDescr = vRs.getString( "descr" );
						}
						vRs.close();
						vRs = null;
						vPStmt.close();
						vPStmt = null;
						
						valueXmlString.append("<site_code_descr>").append("<![CDATA[" + ( siteDescr != null ? siteDescr.trim() : ""  )+ "]]>").append("</site_code_descr>");
					}
					if (currentColumn.trim().equals( "site_code__mfg" ))
					{
						String vSql = null;
						String siteDescr = null;
						vSql = "select descr from site where site_code = '" + ( columnValue != null ? columnValue.trim() : "" ) + "'";
						vPStmt = conn.prepareStatement( vSql );
						vRs = vPStmt.executeQuery();
						if( vRs.next() )
						{
							siteDescr = vRs.getString( "descr" );
						}
						vRs.close();
						vRs = null;
						vPStmt.close();
						vPStmt = null;
						
						valueXmlString.append("<site_mfg_descr>").append("<![CDATA[" + ( siteDescr != null ? siteDescr.trim() : ""  )+ "]]>").append("</site_mfg_descr>");
					}
					if (currentColumn.trim().equals( "item_code" ))
					{
						String vSql = null;
						String itemDescr = null;
						String itemUnit = null;
						vSql = "select descr, unit from item where item_code = '" + ( columnValue != null ? columnValue.trim() : "" ) + "'";
						vPStmt = conn.prepareStatement( vSql );
						vRs = vPStmt.executeQuery();
						if( vRs.next() )
						{
							itemDescr = vRs.getString( "descr" );
							itemUnit = vRs.getString( "unit" );
						}
						vRs.close();
						vRs = null;
						vPStmt.close();
						vPStmt = null;
						
						valueXmlString.append("<item_code_descr>").append("<![CDATA[" + ( itemDescr != null ? itemDescr.trim() : ""  )+ "]]>").append("</item_code_descr>");
						valueXmlString.append("<item_unit>").append("<![CDATA[" + ( itemUnit != null ? itemUnit.trim() : ""  )+ "]]>").append("</item_unit>");
					}
					
					if( currentColumn.trim().equals( "supp_code__mnfr" ) )
					{
						String vSql = null;
						String suppName = null;
						vSql = "select supp_name from supplier where supp_code = '" + ( columnValue != null ? columnValue : "" ) + "'";
						vPStmt = conn.prepareStatement( vSql );
						vRs = vPStmt.executeQuery();
						if( vRs.next() )
						{
							suppName = vRs.getString( "supp_name" );
						}
						vRs.close();
						vRs = null;
						vPStmt.close();
						vPStmt = null;
						
						valueXmlString.append("<supp_name>").append("<![CDATA[" + ( suppName != null ? suppName.trim() : ""  )+ "]]>").append("</supp_name>");
					}					
					valueXmlString.append("</Detail1>");					
					valueXmlString.append("</Root>");
					break;
					
			}//END OF SWITCH
		}//END OF TRY
		catch(Exception e)
		{
			System.out.println("Exception ::"+ e.getMessage());
			e.printStackTrace();
		}
		finally
		{
			try
			{
				if ( vRs != null )
				{
					vRs.close();
					vRs = null;
				}
				if ( vPStmt != null )
				{
					vPStmt.close();
					vPStmt = null;					
				}
				if ( conn != null )
				{
					conn.close();
					conn = null;
				}
			}
			catch(Exception e)
			{
				System.out.println("Exception ::" + e);
				e.printStackTrace();
			}			
		}
		return valueXmlString.toString();
	}//END OF ITEMCHANGE
	private String getCurrdateAppFormat()
	{
		String s = "";
		GenericUtility genericUtility = GenericUtility.getInstance();
		try
		{
			java.util.Date date = null;
			Timestamp timestamp = new Timestamp(System.currentTimeMillis());
			System.out.println(genericUtility.getDBDateFormat());

			SimpleDateFormat simpledateformat = new SimpleDateFormat(genericUtility.getDBDateFormat());
			date = simpledateformat.parse(timestamp.toString());
			timestamp = Timestamp.valueOf(simpledateformat.format(date).toString() + " 00:00:00.0");
			s = (new SimpleDateFormat(genericUtility.getApplDateFormat())).format(timestamp).toString();
		}
		catch(Exception exception)
		{
			System.out.println("Exception in  getCurrdateAppFormat " + exception.getMessage());
		}
		return s;
	}	
	private String isValidPeriod( Document dom1, Connection conn ) throws Exception
	{
		String itemCode = null ,
			   siteCodeMfg = null ,
			   tranId = null ,
			   effFrom = null ,
			   validUpto = null;
		Timestamp effFromDate = null ,
				  validUptoDate = null;
		int cnt = 0;
		
		String errCode = null;
		String errString = null;
		String sql = null;
		PreparedStatement pstmt=null;
		ResultSet rs = null;
		
		itemCode = genericUtility.getColumnValue( "item_code", dom1 );
		tranId = genericUtility.getColumnValue( "tran_id", dom1 );
		siteCodeMfg = genericUtility.getColumnValue( "site_code__mfg", dom1 );
		effFrom = genericUtility.getColumnValue( "eff_from" , dom1 );
		validUpto = genericUtility.getColumnValue( "valid_upto" , dom1 );
		effFromDate = Timestamp.valueOf(genericUtility.getValidDateString(effFrom,genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat())+ " 00:00:00.0");
		validUptoDate = Timestamp.valueOf(genericUtility.getValidDateString(validUpto,genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat())+ " 00:00:00.0");
		
		sql = " select count(*) from batchsize_aprv "
			 +"	where site_code__mfg = '"+ siteCodeMfg +"' "
			 +"	and item_code = '" + itemCode + "' "
			 +"	and ( ? BETWEEN eff_from and valid_upto " 
			 +"	OR  ? BETWEEN eff_from and valid_upto )";
			 
		if( tranId != null && tranId.trim().length() > 0 )
		{
			sql = sql + " and tran_id <> '" + tranId + "' ";
		}
		pstmt = conn.prepareStatement( sql );
		pstmt.setTimestamp( 1, effFromDate );
		pstmt.setTimestamp( 2, validUptoDate );
		rs = pstmt.executeQuery();
		cnt = 0;
		if( rs.next() )
		{
			cnt = rs.getInt( 1 );
		} 
		if( cnt > 0 )
		{
			errCode = "VMINVEFUP";
			errString = getErrorString( "valid_upto", errCode, userId );
		}
		rs.close();
		rs = null;	
		return errCode;
	}
}
