/********************************************************
	Title : WoFirmplanIC
	Date  : 15/10/14
	Developer: manohar

 ********************************************************/
package ibase.webitm.ejb.mfg;
import ibase.system.config.ConnDriver;
import ibase.webitm.ejb.ValidatorEJB;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;

import java.text.SimpleDateFormat;
import java.util.*;
import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


import javax.ejb.Stateless; 
@Stateless 

public class WoFirmplanIC extends ValidatorEJB implements WoFirmplanICLocal, WoFirmplanICRemote
{
	GenericUtility genericUtility = GenericUtility.getInstance();

	public String wfValData(String xmlString, String xmlString1, String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		String errString = "";
		Document dom = null;
		Document dom1 = null;
		try
		{
			if (xmlString != null && xmlString.trim().length() > 0 )
			{
				dom = parseString(xmlString);
				System.out.println("xmlString["+xmlString+"]");
			}
			if (xmlString1 != null && xmlString1.trim().length() > 0 )
			{
				dom1 = parseString(xmlString1);
				System.out.println("xmlString1["+xmlString1+"]");
			}
			
			errString = wfValData(dom, dom1, objContext, editFlag, xtraParams);
		}
		catch(Exception e)
		{
			System.out.println("Exception : [Firmplan][wfValData( String, String )] :==>\n" + e.getMessage());
			throw new ITMException(e);
		}
		return(errString);
	}
	public String wfValData(Document dom, Document dom1, String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
			String childNodeName = null;
			String errString = "";
			String errCode = "";
			String userId = "";
			String sql = "";
			String errorType = "";
			int cnt = 0;
			int ctr=0;
			int childNodeListLength;
			NodeList parentNodeList = null;
			NodeList childNodeList = null;	
			Node parentNode = null;
			Node childNode = null;
			ArrayList<String> errList = new ArrayList<String>();
			ArrayList<String> errFields = new ArrayList<String>();
			Connection conn = null;
			PreparedStatement pstmt = null ;
			ResultSet rs = null;
			ConnDriver connDriver = new ConnDriver();
			StringBuffer errStringXml = new StringBuffer("<?xml version = \"1.0\"?> \r\n <Root> <Errors>");
			
			int currentFormNo =0;
			
			String loginSiteCode="",workOrder="",campgnNo="";
			try
			{
				System.out.println("@@@@@@@@ wfvaldata called");
				conn = connDriver.getConnectDB("DriverITM");
				connDriver = null;
				userId = getValueFromXTRA_PARAMS(xtraParams,"loginCode");
				loginSiteCode = checkNull(genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginSiteCode"));
				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);
						childNodeName = childNode.getNodeName();
						
						
					if(childNodeName.equalsIgnoreCase("work_order"))
					{
						workOrder = checkNull(genericUtility.getColumnValue("work_order", dom));
						campgnNo = checkNull(genericUtility.getColumnValue("campgn_no", dom));

						if (workOrder != null && workOrder.trim().length() > 0 && campgnNo != null && campgnNo.trim().length() > 0)
						{
							errCode = "INVTRANS";
							errList.add(errCode);
							errFields.add(childNodeName.toLowerCase());
						}
						if((workOrder==null || workOrder.trim().length()==0) && (campgnNo==null|| campgnNo.trim().length()==0))
						{
							errCode = "VTCMPWORD";
							errList.add(errCode);
							errFields.add(childNodeName.toLowerCase());
						}
						if(workOrder!=null && workOrder.trim().length()>0)
						 {
							 if (!(isExist(conn, "workorder", "work_order", workOrder)))
								{
								 	errCode = "VTWORDNO";
									errList.add(errCode);
									errFields.add(childNodeName.toLowerCase());
								}				 
						 }
					}
					if(childNodeName.equalsIgnoreCase("campgn_no"))
					{
						workOrder = checkNull(genericUtility.getColumnValue("work_order", dom));
						campgnNo = checkNull(genericUtility.getColumnValue("campgn_no", dom));
						if(campgnNo!=null && campgnNo.trim().length()>0)
						 {
							 if (!(isExist(conn, "workorder", "campgn_no", campgnNo)))
								{
								 	errCode = "VTCMPGNO";
									errList.add(errCode);
									errFields.add(childNodeName.toLowerCase());
								}				 
						 }
					}
						
					}// end for
					break;  // case 1 end
				}
	
				int errListSize = errList.size();
				cnt = 0;
				String errFldName = null;
				if(errList != null && errListSize > 0)
				{
					for(cnt = 0; cnt < errListSize; cnt ++)
					{
						errCode = errList.get(cnt);
						errFldName = errFields.get(cnt);
						System.out.println("errCode .........." + errCode);
						errString = getErrorString(errFldName, errCode, userId);
						errorType = 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);
							errString = "";
						}
						if(errorType.equalsIgnoreCase("E"))
						{
							break;
						}
					}
					errList.clear();
					errList = null;
					errFields.clear();
					errFields = null;
					errStringXml.append("</Errors> </Root> \r\n");
				}
				else
				{
					errStringXml = new StringBuffer("");
				}
			}
			catch(Exception e)
			{
				e.printStackTrace();
				errString = e.getMessage();
				throw new ITMException(e);
			}
			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();
					throw new ITMException(d);
				}
			}
			errString = errStringXml.toString();
			return errString;
		}

	//end of validation

	// method for item change
	public String itemChanged(String xmlString, String xmlString1, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException, ITMException
	{
		Document dom = null;
		Document dom1 = null;
		String valueXmlString = "";
		System.out.println("xmlString.............["+xmlString + "]");
		System.out.println("xmlString1............["+xmlString1 + "]");
		try
		{   
			if(xmlString != null && xmlString.trim().length() > 0)
			{
				dom = parseString(xmlString);
			}
			if(xmlString1 != null && xmlString1.trim().length() > 0)
			{
				dom1 = parseString(xmlString1);
			}
			valueXmlString = itemChanged(dom, dom1, objContext, currentColumn, editFlag, xtraParams);
		}
		catch(Exception e)
		{
			System.out.println("Exception : [WoFirmplanIC][itemChanged( String, String )] :==>\n" + e.getMessage());
			throw new ITMException(e);
		}
		return valueXmlString;
	}


	// method for item change
	public String itemChanged(Document dom, Document dom1, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException, ITMException
	{
	String childNodeName = null;
	StringBuffer valueXmlString = new StringBuffer();
	int ctr = 0;
	NodeList parentNodeList = null;
	NodeList childNodeList = null;
	Node parentNode = null;
	Node childNode = null;
	Connection conn = null;
	PreparedStatement pstmt = null;
	ResultSet rs = null ;
	GenericUtility genericUtility = GenericUtility.getInstance();
	ConnDriver connDriver = new ConnDriver();
	
	int currentFormNo =0;
	String columnValue="",workOrder = "",campgnNo = "";
	try
	{
		Calendar currentDate = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getApplDateFormat());
		String sysDate = sdf.format(currentDate.getTime());
		System.out.println("Now the date is :=>  " + sysDate);

		conn = connDriver.getConnectDB("DriverITM");
		conn.setAutoCommit(false);
		connDriver = null;

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

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

		System.out.println("**********ITEMCHANGE FOR CASE"+currentFormNo+"**************");
		switch(currentFormNo)
		{
		case 1 :
			parentNodeList = dom.getElementsByTagName("Detail1");
			parentNode = parentNodeList.item(0);
			childNodeList = parentNode.getChildNodes();
			ctr = 0; 
			valueXmlString.append("<Detail1>");
			int 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(" Itemchanged called for [" + currentColumn + "] ==> [" + columnValue + "]");
			if(currentColumn.trim().equalsIgnoreCase("itm_default"))
			{
				campgnNo = checkNull(genericUtility.getColumnValue("campgn_no", dom));
				workOrder = checkNull(genericUtility.getColumnValue("work_order", dom));
				System.out.println(" Itemchanged called for [" + currentColumn + "] ==> [" + columnValue + "] campgnNo [" + campgnNo + "] workOrder [" + workOrder + "]");
				valueXmlString.append("<campgn_no protect = \"0\">").append("<![CDATA[" + campgnNo + "]]>").append("</campgn_no>");
				valueXmlString.append("<work_order protect = \"0\">").append("<![CDATA[" + workOrder + "]]>").append("</work_order>");
				/*if ( campgnNo != null && !"null".equals(campgnNo) && campgnNo.trim().length() > 0  )
				{
					valueXmlString.append("<work_order protect = \"1\">").append("<![CDATA[ ]]>").append("</work_order>");					
					valueXmlString.append("<campgn_no protect = \"0\">").append("<![CDATA[" + campgnNo + "]]>").append("</campgn_no>");					
				}
				else
				{
					valueXmlString.append("<work_order protect = \"0\">").append("<![CDATA[" + workOrder + "]]>").append("</work_order>");					
					valueXmlString.append("<campgn_no protect = \"1\">").append("<![CDATA[ ]]>").append("</campgn_no>");					
				}*/
								
			}
			/*else if(currentColumn.trim().equalsIgnoreCase("campgn_no"))
			{
				campgnNo = checkNull(genericUtility.getColumnValue("campgn_no", dom));
				workOrder = checkNull(genericUtility.getColumnValue("work_order", dom));
				System.out.println("campgnNo["+campgnNo+"]>>>>>>>>>>>>>workOrder["+workOrder+"]");
				if ( campgnNo != null && !"null".equals(campgnNo) && campgnNo.trim().length() > 0  )
				{
					valueXmlString.append("<work_order protect = \"1\">").append("<![CDATA[]]>").append("</work_order>");
				}
				else
				{
					valueXmlString.append("<work_order protect = \"0\">").append("<![CDATA[" + workOrder + "]]>").append("</work_order>");
				}
								
			}*/

			valueXmlString.append("</Detail1>");
			break;

		}	
		valueXmlString.append("</Root>");
		System.out.println(" Itemchanged called for [" + currentColumn + "] valueXmlString [" + valueXmlString.toString() + "]");
	}
	catch(Exception e)
	{
		e.printStackTrace();
		System.out.println("Exception ::"+ e.getMessage());
		throw new ITMException(e);
	}
	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();
		}			
	}
	return valueXmlString.toString();
}
	private String checkNull(String input) 
	{
		if(input == null)
		{
			input = "";
		}
		return input;
	}
	private boolean isExist(Connection conn, String tableName, String columnName, String value) throws ITMException, RemoteException
	{
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = "";
		boolean status = false;
		try
		{
			sql = "SELECT count(*) from " + tableName + " where " + columnName + "  = ? ";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, value);
			rs = pstmt.executeQuery();

			if (rs.next())
			{
				if (rs.getBoolean(1))
				{
					status = true;
				}
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;
		} catch (Exception e)
		{
			System.out.println("Exception in isExist ");
			e.printStackTrace();
			throw new ITMException(e);
		}
		System.out.println("returning String from isExist ");
		return status;
	}
	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();
			if(rs.next())
			{
				msgType = rs.getString("MSG_TYPE");
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;
		}
		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;
	}



}	
