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 BusinessUnits
 */
@Stateless
public class BusinessUnits extends ValidatorEJB implements BusinessUnitsRemote, BusinessUnitsLocal 
{
	public String itemChanged() throws RemoteException, ITMException 
	{
		return "";
	}

	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 = "";

		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);
			}
			valueXmlString = itemChanged(dom, dom1, dom2, objContext, currentColumn, editFlag, xtraParams);
		} 
		catch (Exception e) 
		{
			System.out.println("Exception : BusinessUnits : [itemChanged(String, xmlString)] :==>\n" + e.getMessage());
			e.printStackTrace();
		}
		return valueXmlString;
	}
	
	public String itemChanged(Document dom, Document dom1, Document dom2,
			String objContext, String currentColumn, String editFlag,
			String xtraParams) throws RemoteException, ITMException 
	{
		GenericUtility genericUtility = null;
		Connection conn = null;
		int currentFormNo = 0;
		ResultSet rs = null;
		String empCodeHead = "", empFName = "", empMName = "", empLName = "";
		String query = "";
		PreparedStatement pstmt = null;
		StringBuffer valueXmlString;
		try 
		{
			valueXmlString = new StringBuffer();
			genericUtility = GenericUtility.getInstance();
			ConnDriver connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("DriverITM");
			conn.setAutoCommit(false);

			valueXmlString = new StringBuffer(
					"<?xml version=\"1.0\"?><Root><header><editFlag>");
			valueXmlString.append(editFlag).append("</editFlag></header>");

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

			switch (currentFormNo) 
			{
				case 1:
					valueXmlString.append("<Detail1>");
					if(currentColumn.trim().equalsIgnoreCase("emp_code__head"))
					{
						empCodeHead = checkNull(genericUtility.getColumnValue("emp_code__head", dom));
						query = " select emp_fname, emp_mname, emp_lname from employee where emp_code = ? ";
						pstmt = conn.prepareStatement(query);
						pstmt.setString(1, empCodeHead);
						rs = pstmt.executeQuery();
						if (rs.next()) 
						{
							empFName = checkNull(rs.getString("emp_fname"));
							empMName = checkNull(rs.getString("emp_mname"));
							empLName = checkNull(rs.getString("emp_lname"));
						}
						if (rs != null) 
						{
							rs.close();
							rs = null;
						}
						if (pstmt != null) 
						{
							pstmt.close();
							pstmt = null;
						}
						if(empMName.equalsIgnoreCase(""))
						{
							valueXmlString.append("<employee_name>").append("<![CDATA[" + empFName + " " + empLName + "]]>").append("</employee_name>");
						}
						else
						{
							valueXmlString.append("<employee_name>").append("<![CDATA[" + empFName + " " + empMName + " " + empLName + "]]>").append("</employee_name>");
						}
					}
					valueXmlString.append("</Detail1>");

					break;
				}
				valueXmlString.append("</Root>");
			} 
		catch (Exception e) 
		{
			e.printStackTrace();
			System.out.println("Exception ::" + e.getMessage());
			throw new ITMException(e);
		} 
		finally 
		{
			try 
			{
				if (conn != null)
				{
					conn.close();
					conn = null;
				}
			} catch (Exception e1) 
			{
				e1.printStackTrace();
			}
		}
		System.out.println("valueXmlString:::::" + valueXmlString.toString());
		return valueXmlString.toString();
	}
	
	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("bu_code")) 
						{
							String buCode = checkNull(genericUtility.getColumnValue("bu_code", dom));
							
							if (buCode.length() == 0) 
							{
								System.out.println("Unit Code is null");

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

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

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

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

								String sql = " select count(1) as RowCount from business_units where bu_code = ? ";
								pstmt = conn.prepareStatement(sql);
								pstmt.setString(1, buCode);
								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("Unit Code error message");

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

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

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

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

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

								String sql = " select count(1) as RowCount from business_units where descr = ? ";
								pstmt = conn.prepareStatement(sql);
								pstmt.setString(1, descr);
								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("VMBUSUNI08");
									errFields.add(childNodeName.toLowerCase());

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

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

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

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

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

								String sql = " select count(1) as RowCount from business_units where sh_descr = ? ";
								pstmt = conn.prepareStatement(sql);
								pstmt.setString(1, shDescr);
								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("VMBUSUNI09");
									errFields.add(childNodeName.toLowerCase());

									msgType = errorType(conn, "VMBUSUNI09");
									if (msgType.equalsIgnoreCase("E")) 
									{
										break;
									}
								}
							}
						} 
						else if (childNodeName.equalsIgnoreCase("emp_code__head")) 
						{
							String empCodeHead = checkNull(genericUtility.getColumnValue("emp_code__head", dom));
							
							if (empCodeHead.length() == 0) 
							{
								errList.add("VMBUSUNI05");
								errFields.add(childNodeName.toLowerCase());

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

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

								String sql = " select count(1) as RowCount from employee where emp_code = ? ";
								pstmt = conn.prepareStatement(sql);
								pstmt.setString(1, empCodeHead);
								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 < 1) 
								{
									System.out.println("Employee Code error message");

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

									msgType = errorType(conn, "VMBUSUNI06");
									if (msgType.equalsIgnoreCase("E")) 
									{
										break;
									}
								}
								
								
								String relieveDate = "";
								String query = " select relieve_date from employee where emp_code = ? ";
								pstmt = conn.prepareStatement(query);
								pstmt.setString(1, empCodeHead);
								rs = pstmt.executeQuery();

								if (rs.next()) 
								{
									relieveDate = checkNull(rs.getString("relieve_date"));
								}

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

								if (!relieveDate.equalsIgnoreCase("")) 
								{
									System.out.println("Employee Code about to be relieved");

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

									msgType = errorType(conn, "VMBUSUNI07");
									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;
	}
	
}
