package ibase.webitm.ejb.adm;

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

import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.ejb.Stateless;

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

@Stateless
public class UpdateNoOfCVIC extends ValidatorEJB implements UpdateNoOfCVICLocal,UpdateNoOfCVICRemote
{
	Connection conn = null;
	PreparedStatement pstmt=null;
	ResultSet rs = null;
	String sql=null;
	ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
	GenericUtility genericUtility = GenericUtility.getInstance();
	
	String userId = null;
	String empCodeAprv= null;
	String loginSite = null;
	
	public String wfValData() throws RemoteException,ITMException{return "";}
	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
		{
		
			System.out.println("xmlString:::" + xmlString);
			System.out.println("xmlString1:::" + xmlString1);
			System.out.println("xmlString2:::" + xmlString2);
			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 : [UpdateNoOfCVIC][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
	{
		System.out.println("Item Changes Call..................");
		String recvDateStr="",vacNo="",noCvRecd="";		
		int currentFormNo =0;
		ConnDriver connDriver = null;
		PreparedStatement pstmt=null;
		ResultSet rs = null;
		String vacNum = "",childNodeName = "",noCVrcvdStr="",columnValue="";
		String sql="";
		int noCvRecvd = 0,childListLength=0,ctr=0;
		NodeList parentNodeList = null,childNodeList = null;
		Node parentNode = null,childNode = null;
		userId = getValueFromXTRA_PARAMS(xtraParams,"userId");
		empCodeAprv= getValueFromXTRA_PARAMS(xtraParams,"loginEmpCode");
		loginSite = getValueFromXTRA_PARAMS(xtraParams,"loginSiteCode");
	

		StringBuffer valueXmlString = new StringBuffer();
		try{
			
			String objNameDefault = checkNull(getObjName(dom ,objContext));
			SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getApplDateFormat());
			
			
			if (objContext != null && objContext.trim().length() > 0 )
			{
				try
				{
					currentFormNo = Integer.parseInt(objContext);
				}
				catch(Exception e)
				{
					throw new ITMException(e);
				}
			}
			connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("Driver");		
							
			valueXmlString = new StringBuffer("<?xml version=\"1.0\"?><Root><header><editFlag>");
			valueXmlString.append(editFlag).append("</editFlag></header>");
			switch (currentFormNo)
			{
				case 1:	
				{
					System.out.println("currentColumn::::::"+currentColumn);
					valueXmlString.append("<Detail>\r\n");
					if(currentColumn.equalsIgnoreCase("itm_default"))
					{
						java.util.Date recvDate = new java.util.Date();	
						try
						{
							recvDateStr = checkNull(sdf.format(recvDate));	
						}
						catch(Exception e)
						{
							throw new ITMException(e);
						}
						if(recvDateStr != null && recvDateStr.trim().length() > 0)
						{	
							vacNum = checkNull(genericUtility.getColumnValue("vacno", dom));
							sql = "SELECT NO_CV_RECD FROM MPREQ_CVRECD WHERE VAC_NO=? AND RECD_DATE=?";
							pstmt=conn.prepareStatement(sql);
							pstmt.setString(1, vacNum);
							pstmt.setString(2, recvDateStr);
							rs=pstmt.executeQuery();			
							while(rs.next())
							{
								noCvRecvd = rs.getInt("NO_CV_RECD");
							}
							close(pstmt, rs);
														
						}
						valueXmlString.append("<recd_date><![CDATA["+recvDateStr+"]]></recd_date>\r\n");
						valueXmlString.append("<vacno><![CDATA["+vacNum+"]]></vacno>\r\n");
						valueXmlString.append("<no_cv_recd><![CDATA["+noCvRecvd+"]]></no_cv_recd>\r\n");
					}
					if(currentColumn.equalsIgnoreCase("recd_date"))
					{
						System.out.println("Inside recd_date itemchange");
						recvDateStr = checkNull(genericUtility.getColumnValue("recd_date", dom));
						if(recvDateStr.trim().length() > 0)
						{
							vacNum = checkNull(genericUtility.getColumnValue("vacno", dom));
							sql = "SELECT NO_CV_RECD FROM MPREQ_CVRECD WHERE VAC_NO=? AND RECD_DATE=?";
							pstmt=conn.prepareStatement(sql);
							pstmt.setString(1, vacNum);
							pstmt.setString(2, recvDateStr);
							rs=pstmt.executeQuery();			
							while(rs.next())
							{
								noCvRecvd = rs.getInt("NO_CV_RECD");
							}
							close(pstmt, rs);
														
						}
						valueXmlString.append("<recd_date><![CDATA["+recvDateStr+"]]></recd_date>\r\n");
						valueXmlString.append("<vacno><![CDATA["+vacNum+"]]></vacno>\r\n");
						valueXmlString.append("<no_cv_recd><![CDATA["+noCvRecvd+"]]></no_cv_recd>\r\n");
					}
					valueXmlString.append ("</Detail>\r\n");	
				}
			
			break;
			}
	    	
		}
		catch(Exception e)
		{
			throw new ITMException(e);
		}
		finally
		{     
			try
			{
				close(pstmt, rs);
				if(conn != null)
				{
					conn.close();
					conn = null;
				}	
				
	        }
			catch(Exception e)
			{
				System.out.println(e.getMessage());
			}
		}
		valueXmlString.append("</Root>\r\n");
		System.out.println("MPR cv received :itemChanged(Document,String):return valueXmlString"+valueXmlString);
		return valueXmlString.toString();
	}
	//Validtion
	
	
	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
		{
			System.out.println("MprRequirement:wfValData value of xmlString ["+xmlString+"]");
			System.out.println("MprRequirement:wfValData value of xmlString ["+xmlString1+"]");
			System.out.println("MprRequirement:wfValData value of xmlString ["+xmlString2+"]");
			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); 
			}
			errString = wfValData(dom, dom1, dom2, objContext, editFlag, xtraParams);
			System.out.println ("ErrString: " + errString);
		}
		catch (Exception e)
		{
			System.out.println ("Exception: MprRequirement: wfValData(String xmlString): " + e.getMessage() + ":");
			errString = genericUtility.createErrorString(e);
			e.printStackTrace();
		}
		System.out.println ("Returning from MprRequirement wfValData");
		return (errString);  
	}
	public String wfValData(Document dom, Document dom1,Document dom2, String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		String childNodeName = null,childNodeValue = null;
		String vacNum="",errString="",recvDate="",noCvRecvdStr="",recvDateStr="";
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		Connection conn = null;
		int currentFormNo =0 , childNodeListLength= 0 , ctr=0 , noCvRecvd = 0, noCvRecvdData = 0;
		try
		{
			System.out.println("INside try::::::::::::::::::");
			ConnDriver connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("DriverITM");			
			SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getApplDateFormat());	
			System.out.println("objContext::::::::::"+objContext);
			ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
			if (objContext != null && objContext.trim().length() > 0 )
			{
				try
				{
					currentFormNo = Integer.parseInt(objContext);
				}
				catch(Exception e)
				{
					throw new ITMException(e);
				}
			}
			System.out.println(" ***********Validation for MprRequirement Detail  "+currentFormNo);
			switch(currentFormNo)
			{
			
				case 1:
				{
					parentNodeList = dom.getElementsByTagName("Detail1");
					parentNode = parentNodeList.item(0);
				    childNodeList = parentNode.getChildNodes();
					childNodeListLength = childNodeList.getLength();
					System.out.println("child Node List Length::::::"+childNodeListLength);
					for(ctr = 0; ctr < childNodeListLength; ctr++)
					{	
						
						childNode = childNodeList.item(ctr);
						System.out.println("childNode"+childNode);
						if( childNode.getNodeType() != Node.ELEMENT_NODE )
						{
							continue;
						}

						childNodeName = childNode.getNodeName();
						if(childNode.getFirstChild()!= null)
						{
							childNodeValue = childNode.getFirstChild().getNodeValue();
						}
						if(childNodeName.equalsIgnoreCase("vacno"))
						{
							vacNum = checkNull(genericUtility.getColumnValue("vacno", dom));
							if(vacNum.trim().length() == 0)
							{
								System.out.println("Vacancy Number is Null................");
								errString = itmDBAccessEJB.getErrorString("","VTMPRVACNO","","",conn);
								return errString;
							}
						}
						if(childNodeName.equalsIgnoreCase("recd_date"))
						{
							recvDate = checkNull(genericUtility.getColumnValue("recd_date", dom));
							if(recvDate.trim().length() == 0)
							{
								System.out.println("Recieved date is Null................");
								errString = itmDBAccessEJB.getErrorString("","VTRCVDATE","","",conn);
								return errString;
							}
						}
						if(childNodeName.equalsIgnoreCase("no_cv_recd"))
						{
							System.out.println("Inside no_cv_recd validation:::");
							noCvRecvdStr = checkNull(genericUtility.getColumnValue("no_cv_recd", dom));
							System.out.println("noCvRecvdStr::::::::"+noCvRecvdStr);
							if(noCvRecvdStr.trim().length() == 0)
							{
								System.out.println("Recieved date is Null................");
								errString = itmDBAccessEJB.getErrorString("","VPCVRECV04","","",conn);
								return errString;
							}
							else
							{
								try
								{
									noCvRecvd = Integer.parseInt(noCvRecvdStr);
								}
								catch(Exception e)
								{
									throw new ITMException(e);
								}
								recvDate = checkNull(genericUtility.getColumnValue("recd_date", dom));
								vacNum = checkNull(genericUtility.getColumnValue("vacNo", dom));
								if(noCvRecvd == 0)
								{
									vacNum = checkNull(genericUtility.getColumnValue("vacNo", dom));
									String sql = "SELECT NO_CV_RECD FROM MPREQ_CVRECD WHERE VAC_NO=? AND RECD_DATE=?";
									pstmt=conn.prepareStatement(sql);
									pstmt.setString(1, vacNum);
									pstmt.setString(2, recvDateStr);
									rs=pstmt.executeQuery();			
									while(rs.next())
									{
										noCvRecvdData = rs.getInt("NO_CV_RECD");
									}
									close(pstmt, rs);
									if(noCvRecvdData > 0)
									{
										System.out.println("Recieved date is not valid................");
										errString = itmDBAccessEJB.getErrorString("","VPCVRECV04","","",conn);
										return errString;
									}
								}
							}
						}
					}
				}
				break;
			}
		}
		catch(Exception e)
		{
			throw new ITMException(e);
		}
		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)
			{
				e.printStackTrace();
				throw new ITMException(e);
			}
		}
		System.out.println("ErrString ::"+errString);
		return errString;
	}
	private String getObjName(Document dom2,String objContext)// Method to get object name
	{	
		Node elementName = null;
		NodeList elementList = null;
		String objName = "";
		elementList = dom2.getElementsByTagName("Detail"+objContext);
		elementName = elementList.item(0);
		if (elementName!=null && ("Detail"+objContext).equalsIgnoreCase(elementName.getNodeName()))
		{
			NamedNodeMap etlAttributes = elementName.getAttributes();
			if (etlAttributes!=null)
			{
				if (etlAttributes.getNamedItem("objName")!=null)
				{
					objName = etlAttributes.getNamedItem("objName").getNodeValue();
				}
			}
		}
		return objName;
	}
	private String checkNull(String input)//Method to check null string
	{
		if (input == null)
		{
			input = "";
		}
		else
		{
			input =input.trim();
		}
		return input;
	}
	
	private void close(PreparedStatement pstmt,ResultSet rs) //Method to close PreparedStatement & ResultSet
	{
		try
		{
				if( rs != null)
				{
					rs.close();
					rs = null;
				}
				if( pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
}
