package ibase.webitm.ejb.adm;

import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import ibase.system.config.ConnDriver;
import ibase.utility.GenericUtility;
import ibase.webitm.ejb.ValidatorEJB;
import ibase.webitm.utility.ITMException;

import javax.ejb.Stateless;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * Session Bean implementation class BusinessFunction
 */
@Stateless
public class BusinessFunction extends ValidatorEJB implements BusinessFunctionRemote, BusinessFunctionLocal 
{	
	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;
		String errString = "";
		GenericUtility genericUtility = GenericUtility.getInstance();
		try 
		{
			if (xmlString != null && xmlString.trim().length() != 0) 
			{
				dom = parseString(xmlString);
			}
			if (xmlString1 != null && xmlString1.trim().length() != 0) 
			{
				dom1 = parseString(xmlString1);
			}
			if (xmlString2 != null && xmlString2.trim().length() > 0) 
			{
				dom2 = parseString(xmlString2);
			}
			errString = wfValData(dom, dom1, dom2, objContext, editFlag, xtraParams);
		} 
		catch (Exception e) 
		{
			System.out.println("Exception : StdPayStru : wfValData(String xmlString) : ==>" + e.getMessage());
			errString = genericUtility.createErrorString(e);
			e.printStackTrace();
		}
		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;
		int currentFormNo = 0, childNodeListLength = 0;
		String userId = "";
		String childNodeName = null;
		String errString = "";
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;

		String msgType = "";

		GenericUtility genericUtility = null;

		ArrayList<String> errList = new ArrayList<String>();
		ArrayList<String> errFields = new ArrayList<String>();

		try 
		{
			ConnDriver connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("DriverITM");
			conn.setAutoCommit(false);		
			
			genericUtility = GenericUtility.getInstance();
			userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginCode");

			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 (int ctr = 0; ctr < childNodeListLength; ctr++) 
					{
						childNode = childNodeList.item(ctr);
						if (childNode.getNodeType() != Node.ELEMENT_NODE) 
						{
							continue;
						}
						childNodeName = childNode.getNodeName();

						System.out.println("childNodeName.editFlag." + childNodeName + ".." + editFlag);

						if (childNodeName.equalsIgnoreCase("func_code")) 
						{
							String fnCode = checkNull(genericUtility.getColumnValue("func_code", dom));
							
							if (fnCode.length() == 0) 
							{
								System.out.println("Function Code is null");

								errList.add("VMBUFUNC01");
								errFields.add(childNodeName.toLowerCase());

								msgType = errorType(conn, "VMBUFUNC01");
								if (msgType.equalsIgnoreCase("E")) 
								{
									break;
								}
							}

							else if(editFlag.equalsIgnoreCase("A"))
							{
								int rowCount = 0;

								System.out.println("Function Code invalid");

								String sql = " select count(1) as RowCount from busi_functions where func_code = ? ";
								pstmt = conn.prepareStatement(sql);
								pstmt.setString(1, fnCode);
								rs = pstmt.executeQuery();

								if (rs.next()) 
								{
									rowCount = rs.getInt("RowCount");
								}

								if (rs != null) 
								{
									rs.close();
									rs = null;
								}
								if (pstmt != null) 
								{
									pstmt.close();
									pstmt = null;
								}

								if (rowCount > 0) 
								{
									System.out.println("Function Code error message");

									errList.add("VMBUFUNC02");
									errFields.add(childNodeName.toLowerCase());

									msgType = errorType(conn, "VMBUFUNC02");
									if (msgType.equalsIgnoreCase("E")) 
									{
										break;
									}
								}
							}
						} 
						else if (childNodeName.equalsIgnoreCase("descr")) 
						{
							String descr = checkNull(genericUtility.getColumnValue("descr", dom));
							String fnCode = checkNull(genericUtility.getColumnValue("func_code", dom));
							
							if (descr.length() == 0) 
							{
								System.out.println("Description is null");

								errList.add("VMBUFUNC03");
								errFields.add(childNodeName.toLowerCase());

								msgType = errorType(conn, "VMBUFUNC03");
								if (msgType.equalsIgnoreCase("E")) 
								{
									break;
								}
							}
							else
							{
								int rowCount = 0;

								System.out.println("Description invalid");

								String sql = " select count(1) as RowCount from busi_functions where descr = ? and func_code <> ?";
								pstmt = conn.prepareStatement(sql);
								pstmt.setString(1, descr);
								pstmt.setString(2, fnCode);
								rs = pstmt.executeQuery();

								if (rs.next()) 
								{
									rowCount = rs.getInt("RowCount");
								}

								if (rs != null) 
								{
									rs.close();
									rs = null;
								}
								if (pstmt != null) 
								{
									pstmt.close();
									pstmt = null;
								}

								if (rowCount > 0) 
								{
									System.out.println("Description error message");

									errList.add("VMBUFUNC04");
									errFields.add(childNodeName.toLowerCase());

									msgType = errorType(conn, "VMBUFUNC04");
									if (msgType.equalsIgnoreCase("E")) 
									{
										break;
									}
								}
							}
						}
						else if (childNodeName.equalsIgnoreCase("sh_descr")) 
						{
							String shDescr = checkNull(genericUtility.getColumnValue("sh_descr", dom));
							String fnCode = checkNull(genericUtility.getColumnValue("func_code", dom));
							
							if (shDescr.length() == 0) 
							{

								System.out.println("Short Description is null");

								errList.add("VMBUFUNC05");
								errFields.add(childNodeName.toLowerCase());

								msgType = errorType(conn, "VMBUFUNC05");
								if (msgType.equalsIgnoreCase("E")) 
								{
									break;
								}
							}
							else
							{
								int rowCount = 0;

								System.out.println("Short Description invalid");

								String sql = " select count(1) as RowCount from busi_functions where sh_descr = ? and func_code <> ? ";
								pstmt = conn.prepareStatement(sql);
								pstmt.setString(1, shDescr);
								pstmt.setString(2, fnCode);
								rs = pstmt.executeQuery();

								if (rs.next()) 
								{
									rowCount = rs.getInt("RowCount");
								}

								if (rs != null) 
								{
									rs.close();
									rs = null;
								}
								if (pstmt != null) 
								{
									pstmt.close();
									pstmt = null;
								}

								if (rowCount > 0) 
								{
									System.out.println("Short Description error message");

									errList.add("VMBUFUNC06");
									errFields.add(childNodeName.toLowerCase());

									msgType = errorType(conn, "VMBUFUNC06");
									if (msgType.equalsIgnoreCase("E")) 
									{
										break;
									}
								}
							}
						}
					}
					break;
				}

				int errListSize = errList.size();
				StringBuffer errStringXml = new StringBuffer("<?xml version=\"1.0\"?>\r\n<Root><Errors>");

				//ERRORLIST
				if (errList != null && errListSize > 0) 
				{
					for (int cnt = 0; cnt < errListSize; cnt++) 
					{
						String errCode = (String) errList.get(cnt);
						String errFldName = (String) errFields.get(cnt);
						System.out.println("errCode .........." + errCode);

						errString = getErrorString(errFldName, errCode, userId);
						System.out.println("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("errStringXml .........." + errStringXml);
							errString = "";
						}
						if (msgType.equalsIgnoreCase("E")) 
						{
							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) 
			{
				System.out.println("Exception ::" + e);
				e.printStackTrace();
				errString = e.getMessage();
			} 
			finally 
			{
				try 
				{
					if (conn != null) 
					{
						if (rs != null)
						{
							rs.close();
							rs = null;
						}
						if(pstmt != null)
						{
							pstmt.close();
							pstmt = null;
						}
						conn.close();
					}
					conn = null;
				} 
				catch (Exception d) 
				{
					d.printStackTrace();
				}
			}
			System.out.println("ErrString ::" + errString);
			return errString;
	}
	
	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");
			}
		} 
		catch (Exception ex) 
		{
			ex.printStackTrace();
			throw new ITMException(ex);
		} 
		finally 
		{
			try 
			{
				if (rs != null) 
				{
					rs.close();
					rs = null;
				}
				if (pstmt != null) 
				{
					pstmt.close();
					pstmt = null;
				}
			} 
			catch (Exception e) 
			{
				e.printStackTrace();
				throw new ITMException(e);
			}
		}
		return msgType;
	}
	
	private String checkNull(String input) 
	{
		if (input == null) 
		{
			input = "";
		} 
		else 
		{
			input = input.trim();
		}
		return input;
	}

}
