package ibase.webitm.ejb.fin;
import javax.ejb.Stateless;



import ibase.system.config.ConnDriver;
import ibase.webitm.ejb.*;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;
import java.rmi.RemoteException;
import java.sql.*;
import java.text.SimpleDateFormat;
import org.w3c.dom.*;

@javax.ejb.Stateless
public class AssetclassIC  extends ValidatorEJB implements AssetclassICLocal ,AssetclassICRemote
{

	GenericUtility genericUtility = GenericUtility.getInstance(); 
	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 : AssetRegisterICEJB : 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;
		String columnValue = null;
		String childNodeName = null;
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
		String errCode = null;
		String userId = null,loginSite = null;
		int cnt = 0;
		int ctr = 0;
		String finEntity = "";
		int currentFormNo = 0;
		int childNodeListLength;
		Connection conn = null;
		PreparedStatement pstmt=null;
		ResultSet rs = null;
		String sql = 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");
			
			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();
						int seriesCount = 0;
						String id = genericUtility.getColumnValue("item_ser", dom);
						String id1 = genericUtility.getColumnValue("grp_code", dom);
						String Sql = "SELECT COUNT(1) AS COUNT FROM ASSET_CLASS WHERE ITEM_SER=? AND GRP_CODE=?";
					    pstmt = conn.prepareStatement(Sql);
					    pstmt.setString(1,id);
					    pstmt.setString(2,id1);
					    rs = pstmt.executeQuery();
						System.out.println("Sql" + Sql);
						if (rs.next()) {
							seriesCount = rs.getInt("COUNT");
						}
						if (seriesCount > 0) {
							errString = getErrorString(" ", "VMTRANIDEX", userId);				
							break;
						}
						if ( childNodeName.equalsIgnoreCase( "item_ser" ) )
						{
							
								if ( childNode.getFirstChild() == null )
								{
									errString =itmDBAccessEJB.getErrorString("item_ser","VMCODNULL",userId);
									break ;
								}
								else
								{
									String itemSer = genericUtility.getColumnValue( "item_ser", dom ) != null ?genericUtility.getColumnValue( "item_ser", dom ).trim() : null;
									sql = "SELECT count(*) from itemser"
									      +" where trim(item_ser) = ? ";
									pstmt = conn.prepareStatement( sql );
									pstmt.setString(1,itemSer);
									rs = pstmt.executeQuery();
									if( rs.next() )
									{
										cnt = rs.getInt( 1 );
									} 
									System.out.println(" COUNT =====> [" + cnt + "]");
									if( cnt == 0 )
									{
										errString =itmDBAccessEJB.getErrorString("item_ser","VTITEMSER1",userId);
										break ;
									}
									rs.close();
									rs = null;
									pstmt.close();
									pstmt = null;
						}
						
						}
						if( childNodeName.equalsIgnoreCase( "grp_code" ))
						{
							if (childNode.getFirstChild() == null) 
							{
								errString = getErrorString("grp_code", "VMGCODNULL", userId);
								break;
							} 
							
						}
						if(childNodeName.equalsIgnoreCase( "fin_entity" ))
						{
							finEntity = this.genericUtility.getColumnValue("fin_entity", dom);
							if(finEntity != null && finEntity.trim().length() > 0)
							{
								sql = "select count(*) from finent where fin_entity = ?";
								pstmt = conn.prepareStatement(sql);
								pstmt.setString(1, finEntity);
								rs = pstmt.executeQuery();
								if (rs.next())
								{
									cnt = rs.getInt(1);
								}
								if (cnt == 0)
								{
									errString = getErrorString("fin_entity", "VMFENTY1", userId);
									/*errCode = "VMFENTY1";
									errList.add(errCode);
									errFields.add(childNodeName.toLowerCase());*/
								}
								rs.close();
								rs = null;
								pstmt.close();
								pstmt = null;
							}		
						}
					}
					break;
			}
			
		}
    	catch(Exception e)
		{
			System.out.println("Exception ::" +e);
			e.printStackTrace();
			errCode = "VALEXCEP";
			errString = getErrorString( "", errCode, userId );									
		}
    	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(" < AssetClassIcEJB > CONNECTION IS CLOSED");
		}
		System.out.println("ErrString ::" + errString);

		return errString;
	}//END OF VALIDATION
	
	
	@Override
	public String itemChanged(String xmlString, String xmlString1, String xmlString2, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException, ITMException 
	 {
		Document dom1 = null;
		Document dom = null;
		Document dom2 = null;
		String valueXmlString = "";
		GenericUtility genericUtility = GenericUtility.getInstance();
		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);
			}
			  valueXmlString = itemChanged(dom, dom1, dom2, objContext, currentColumn, editFlag, xtraParams);
		}
		catch (Exception e) 
		{
			System.out.println("Exception :WsfaGradeTest:itemChanged(String,String,String,String,String,String):" + e.getMessage() + ":");
			valueXmlString = genericUtility.createErrorString(e);
			e.printStackTrace();
		}
		System.out.println("returning from WsfaGradeTest itemChanged");
		return (valueXmlString);
	 }

	@Override
	public String itemChanged(Document dom, Document dom1, Document dom2, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException, ITMException 
	{
		StringBuffer valueXmlString = new StringBuffer();

		Connection conn = null;
		PreparedStatement pStmt = null;
		ResultSet rs = null;
		String sql = "";
		int currentFormNo = 0;

		GenericUtility genericUtility;
		String  grpcode = "", descr = "";
		String  itemser = "", itmdescr = "";
		try 
		{
			genericUtility = GenericUtility.getInstance();
			// siteCode = getValueFromXTRA_PARAMS(xtraParams, "loginSiteCode");

			ConnDriver conndriver = new ConnDriver();
			conn = conndriver.getConnectDB("DriverITM");
			conn.setAutoCommit(false);
			conndriver = null;
			if (objContext != null && objContext.trim().length() > 0)
				currentFormNo = Integer.parseInt(objContext);

			currentColumn = currentColumn == null ? "" : currentColumn.trim();
			System.out.println("currentColumn : " + currentColumn);
			valueXmlString = new StringBuffer("<?xml version=\"1.0\"?><Root><header><editFlag>");
			valueXmlString.append(editFlag).append("</editFlag></header>");
			System.out.println("current form no: " + currentFormNo);
			System.out.println("dom:::::::::: : " + genericUtility.serializeDom(dom));
			System.out.println("dom11111111111111:::::::::: : " + genericUtility.serializeDom(dom1));
			System.out.println("dom222222222222222:::::::::: : " + genericUtility.serializeDom(dom2));

			switch (currentFormNo) 
			{
			case 1:
				valueXmlString.append("<Detail1>");
				if ("itm_default".equalsIgnoreCase(currentColumn))
				{
					System.out.println("itm_default : ");
					System.out.println("Content of xtraParams ..> " + xtraParams);
					//tranDate = (sdf.format(timestamp).toString()).trim();
				} 
				else if (currentColumn.trim().equalsIgnoreCase("item_ser")) 
				 {
					    itemser = genericUtility.getColumnValue("item_ser", dom);
					    itemser = itemser == null ? "" : itemser.trim();
						sql = "select descr from itemser where item_ser =?";
						pStmt = conn.prepareStatement(sql);
						pStmt.setString(1, itemser);
						rs = pStmt.executeQuery();
						if (rs.next())
						{
							itmdescr = rs.getString(1);

						}
						rs.close();
						rs = null;
						pStmt.close();
						pStmt = null;

						itmdescr = itmdescr == null ? "" : itmdescr.trim();

						valueXmlString.append("<itemser_descr>").append(itmdescr).append("</itemser_descr>\r\n");
				 }
				
				 else if (currentColumn.trim().equalsIgnoreCase("grp_code")) 
				{
					
					 /* ls_code     = dw_edit.GetItemString(1,colname)
		                select descr into :ls_descr from gencodes where fld_value = :ls_code ;
		                dw_edit.SetItem(1,'gencodes_descr',ls_descr)*/
					grpcode = genericUtility.getColumnValue("grp_code", dom);
					grpcode = grpcode == null ? "" : grpcode.trim();
					sql = "select descr from gencodes  where fld_value =?";
					pStmt = conn.prepareStatement(sql);
					pStmt.setString(1, grpcode);
					rs = pStmt.executeQuery();
					if (rs.next())
					{
						descr = rs.getString(1);

					}
					rs.close();
					rs = null;
					pStmt.close();
					pStmt = null;

					descr = descr == null ? "" : descr.trim();

					valueXmlString.append("<gencodes_descr>").append(descr).append("</gencodes_descr>\r\n");
				} 
				valueXmlString.append("</Detail1 >");
				break;
			}
			valueXmlString.append("</Root>\r\n");
		}   
		catch (Exception e)
		{
			System.out.println("Exception :AssetClass:itemChange•••••••(Document,String):" + e.getMessage() + ":");
			valueXmlString.delete(0, valueXmlString.length());
			
			e.printStackTrace();
		}
		finally
		{
			try
			{
				if ( rs != null )
				{
					rs.close();
					rs = null;
				}
				if ( pStmt != null )
				{
					pStmt.close();
					pStmt = null;					
				}
				if ( conn != null )
				{
					conn.close();
					conn = null;
				}
			}
			catch(Exception e)
			{
				System.out.println("Exception ::" + e);
				e.printStackTrace();
			}			
		}
		System.out.println("\n***** ValueXmlString :" + valueXmlString + ":*******");
		return valueXmlString.toString();
	}

}
