package ibase.webitm.ejb.adm;

import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.ejb.Stateless;

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

import ibase.system.config.ConnDriver;
import ibase.utility.CommonConstants;
import ibase.webitm.ejb.ITMDBAccessEJB;
import ibase.webitm.ejb.ProcessEJB;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;
//Added By Suraj  [A15BSUN007]   [Start]
@Stateless
public class UpdateNoOfCVPrc extends ProcessEJB implements UpdateNoOfCVPrcLocal,UpdateNoOfCVPrcRemote
{
	GenericUtility genericUtility = GenericUtility.getInstance();
	ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
	Connection conn = null;
	public String getData(String xmlString, String xmlString2, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		//ConnDriver connDriver = new ConnDriver();
		String rtrStr = "";
		Document headerDom = null;
		Document detailDom = null;
		System.out.println("xmlString:::::::::"+xmlString);
		System.out.println("xmlString2:::::::::"+xmlString2);
		System.out.println("windowName:::::::::"+windowName);
		System.out.println("xtraParams:::::::::"+xtraParams);
		try
		{
			if(xmlString != null && xmlString.trim().length()!=0)
			{
				headerDom = genericUtility.parseString(xmlString);
			}
			if(xmlString2 != null && xmlString2.trim().length()!=0)
			{
				detailDom = genericUtility.parseString(xmlString2);
			}
			try
			{
				if(conn==null)
				{
					ConnDriver connDriver = new ConnDriver();
					conn = connDriver.getConnectDB("DriverITM");
					conn.setAutoCommit(false);
					DatabaseMetaData dbmd = conn.getMetaData();
					System.out.println("DriverName["+dbmd.getDriverName() );
					System.out.println("DriverURI["+dbmd.getURL()  );
					System.out.println("DriverUSER["+dbmd.getUserName() );
					System.out.println("ApplDateFormat["+genericUtility.getApplDateFormat());
					System.out.println("DBDateFormat["+genericUtility.getDBDateFormat() );
					connDriver = null;
				}

			}
			catch (Exception e)
			{
				System.out.println("Exception :LeaveEncasePrcEJB getData:==>"+e.getMessage());
			}

			rtrStr = getData(headerDom, detailDom, windowName, xtraParams);
		}
		catch (Exception e)
		{

			rtrStr = e.getMessage();


		}
		return rtrStr;
	}//END OF GETDATA(1)
	
	public String getData(Document headerDom, Document detailDom, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		String vacNo="",recvDateStr="",errString="",resultString="";
		int noCVRcvd=0;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		StringBuffer valueXmlString = new StringBuffer();
		//SimpleDateFormat sdf = new SimpleDateFormat("yyyy-DD-mm");
		//java.util.Date recvDate=null;
		try
		{


			if(conn==null)
			{
				ConnDriver connDriver = new ConnDriver();
				conn = connDriver.getConnectDB("DriverITM");
				conn.setAutoCommit(false);
				DatabaseMetaData dbmd = conn.getMetaData();
				System.out.println("DriverName["+dbmd.getDriverName() );
				System.out.println("DriverURI["+dbmd.getURL()  );
				System.out.println("DriverUSER["+dbmd.getUserName() );
				System.out.println("ApplDateFormat["+genericUtility.getApplDateFormat());
				System.out.println("DBDateFormat["+genericUtility.getDBDateFormat() );
				connDriver = null;
			}
			
			//noCVRcvdStr = genericUtility.getColumnValue("no_cv_recd",headerDom);;
			
			vacNo = genericUtility.getColumnValue("vacno",headerDom);
			
			recvDateStr = genericUtility.getColumnValue("recd_date",headerDom);

			
			/* if(recvDateStr != null || recvDateStr.trim().length() > 0)
			{
				recvDateStr = sdf.format(recvDate);
				System.out.println("recvDateStr inside checknull:::"+recvDateStr);

			}
			System.out.println("recvDateStr"+recvDateStr);

			if ( noCVRcvdStr == null || noCVRcvdStr.trim().length() == 0 )
			{
				System.out.println("cv received is Null............");
				errString = itmDBAccessEJB.getErrorString("","VTCVRCVD","","",conn);
				return errString;
			}*/
			if ( vacNo == null || vacNo.trim().length() == 0 )
			{

				System.out.println("Vacancy Number is Null................");
				errString = itmDBAccessEJB.getErrorString("","VTMPRVACNO","","",conn);
				return errString;
			}
			if ( recvDateStr == null || recvDateStr.trim().length() == 0 )
			{
				System.out.println("Recieved date is Null................");
				errString = itmDBAccessEJB.getErrorString("","VTRCVDATE","","",conn);
				return errString;
			}
			
			int i = 0;
			String sql="SELECT NO_CV_RECD FROM MPREQ_CVRECD WHERE VAC_NO=? AND RECD_DATE=?";
			pstmt=conn.prepareStatement(sql);
			pstmt.setString(1, vacNo);
			pstmt.setString(2, recvDateStr);
			rs=pstmt.executeQuery();
			valueXmlString.append("<?xml version=\"1.0\" encoding='"+CommonConstants.ENCODING+"' ?><DocumentRoot>\r\n");
			valueXmlString.append("<description>Datawindow Root</description>" +
					"<group0><description>Group0 description</description><Header0><description>Header0 members</description>\r\n");


			while(rs.next())
			{
				noCVRcvd = rs.getInt("NO_CV_RECD");
				i = i + 1;
				valueXmlString.append("<Detail1 domID=\"" + i + "\" objName=\"mprqr_cv_rcvd\" objContext=\"1\">\r\n");
				valueXmlString.append("<attribute updateFlag=\"N\" selected=\"N\" />\r\n");
				valueXmlString.append("<vac_no><![CDATA[").append(vacNo == null  ? " ":vacNo).append("]]></vac_no>\r\n");
				valueXmlString.append("<recd_date><![CDATA[").append(recvDateStr == null  ? " ":recvDateStr).append("]]></recd_date>\r\n");
				valueXmlString.append("<no_cv_recd><![CDATA[").append(Integer.toString(noCVRcvd) ).append("]]></no_cv_recd>\r\n");
				valueXmlString.append("</Detail1>\r\n");
			}
			if (rs != null)
			{
				rs.close();
				rs = null;
			}
			if (pstmt != null)
			{
				pstmt.close();
				pstmt = null;
			}
			if (i < 1)
			{
				i = i + 1;
				valueXmlString.append("<Detail1 domID=\"" + i + "\" objName=\"mprqr_cv_rcvd\" objContext=\"1\">\r\n");
				valueXmlString.append("<attribute updateFlag=\"N\" selected=\"N\" />\r\n");
				valueXmlString.append("<vac_no><![CDATA[").append(vacNo == null  ? " ":vacNo).append("]]></vac_no>\r\n");
				valueXmlString.append("<recd_date><![CDATA[").append(recvDateStr == null  ? " ":recvDateStr).append("]]></recd_date>\r\n");
				valueXmlString.append("<no_cv_recd><![CDATA[0]]></no_cv_recd>\r\n");
				valueXmlString.append("</Detail1>\r\n");

			}
		    valueXmlString.append("</Header0>\r\n");
			valueXmlString.append("</group0>\r\n");
			valueXmlString.append("</DocumentRoot>\r\n");
			resultString = valueXmlString.toString();
			System.out.println("ResultString....." + resultString);

		}
		catch(Exception e)
		{
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				//retTabSepStrBuff = null;
				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();
			}
		}
		System.out.println("Return String From Application Server --->>>");
		System.out.println("["+errString+"]");
		return errString;
	}

	public String process(String xmlString, String xmlString2, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		Document detailDom = null;
		Document headerDom = null;
		String retStr = "";
		try
		{
			System.out.println("xmlString[process]::::::::::;;;"+xmlString);
			System.out.println("xmlString2[process]::::::::::;;;"+xmlString2);
			System.out.println("windowName[process]::::::::::;;;"+windowName);
			System.out.println("xtraParams[process]:::::::::;;;"+xtraParams);
			if(xmlString != null && xmlString.trim().length()!=0)
			{
				headerDom = genericUtility.parseString(xmlString);
				System.out.println("headerDom" + headerDom);
			}
			if(xmlString2 != null && xmlString2.trim().length()!=0)
			{
				detailDom = genericUtility.parseString(xmlString2);
				System.out.println("detailDom" + detailDom);
			}
		    retStr = process(headerDom, detailDom, windowName, xtraParams);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return retStr;
	}//END OF PROCESS (1)
   //END By Suraj  [A15BSUN007] [END] 
	public String process(Document headerDom, Document detailDom, String windowName, String xtraParams) throws RemoteException,ITMException
	{

		//Added By Juhi  on  08/12/2015  [A15BSUN007]   [Start]
		System.out.println("\n [UpdateNoOfCVPrc:] Start-Process() Called ::");
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		NodeList parentNodeList = null,childNodeList = null;
		Node parentNode = null,childNode = null;
		int parentNodeListLength = 0,childNodeListLength = 0;
		String vacNo="",recvDateStr="";
		int count = 0,noOfCVRcvd=0,sumNoCVRcvd=0;
		String noCVrcvdStr = "";
		String childNodeName = "",errString="";




	    try
	    {
	    	if (conn == null)
	    	{
				ConnDriver connDriver = new ConnDriver();
				conn = connDriver.getConnectDB("DriverITM");
	    	}
		}
        catch (Exception e)
	    {
        	System.out.println("Exception ::ejbCreate :==>" + e.getMessage());
        	e.printStackTrace();
			throw new ITMException(e);
	    }


	    try
	    {
	    	genericUtility = GenericUtility.getInstance();

	    	System.out.println("getApplDateFormat::::"+genericUtility.getApplDateFormat());
	    	java.sql.Timestamp recvDate = null;String sql="";
	    	parentNodeList = detailDom.getElementsByTagName("Detail1");
	    	parentNodeListLength = parentNodeList.getLength();

	    	for (int i = 0; i < parentNodeListLength; i++)
	    	{
	    		parentNode = parentNodeList.item(i);
	    		childNodeList = parentNode.getChildNodes();
	    		childNodeListLength = childNodeList.getLength();
	    		for (int j = 0; j < childNodeListLength; j++)
	    		{
	    			childNode = childNodeList.item(j);
	    			childNodeName = childNode.getNodeName();
	    			System.out.println("childNodeName: "+childNodeName);
	    			if (childNodeName.equalsIgnoreCase("vacno"))
	    			{
	    				vacNo = childNode.getFirstChild() == null ? "" : childNode.getFirstChild().getNodeValue();
	    			}
	    			else if (childNodeName.equalsIgnoreCase("recd_date"))
	    			{
	    				recvDateStr = childNode.getFirstChild() == null ? "" : childNode.getFirstChild().getNodeValue().trim();
	    			}
	    			else if(childNodeName.equalsIgnoreCase("no_cv_recd"))
	    			{
	    				noCVrcvdStr = childNode.getFirstChild() == null ? "" : childNode.getFirstChild().getNodeValue().trim();
	    				System.out.println("noCVrcvdStr"+noCVrcvdStr);
	    			}
	    	     }
	    		try
	    		{
	    			//Added by suraj [11-02-2016][To validate vacancy number and received date][Start]
	    			if ( vacNo == null || vacNo.trim().length() == 0 )
	    			{

	    				System.out.println("Vacancy Number is Null................");
	    				errString = itmDBAccessEJB.getErrorString("","VTMPRVACNO","","",conn);
	    				return errString;
	    			}
	    			if ( recvDateStr == null || recvDateStr.trim().length() == 0 )
	    			{
	    				System.out.println("Recieved date is Null................");
	    				errString = itmDBAccessEJB.getErrorString("","VTRCVDATE","","",conn);
	    				return errString;
	    			}
	    			//Added by suraj [11-02-2016][To validate vacancy number and received date][End]
	    			if(noCVrcvdStr.contains("."))
	    		    {
	    		    	errString = itmDBAccessEJB.getErrorString("","VPCVRECV04" , "SYSTEM");
	    		    	break;
	    		    }
	    			if(noCVrcvdStr.trim().length() > 0 )
	                {
	    				noOfCVRcvd = Integer.parseInt(noCVrcvdStr);
	    		    }

	    		    System.out.println("noOfCVRcvd after parsing into integer:" + noOfCVRcvd);

	    	    }
	    		catch(Exception e)
	    		{
	    			errString = itmDBAccessEJB.getErrorString("","VPCVRECV04" , "SYSTEM");
					break;
	    		}

	    		System.out.println("vacNo:"+  vacNo +" recd_date: "+recvDateStr+ "noCVRcvd: "+noOfCVRcvd);

	    		try
	    		{
	    			if(recvDateStr.trim().length() > 0 )
	    	        {

	    				recvDate = java.sql.Timestamp.valueOf(genericUtility.getValidDateTimeString(recvDateStr, genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat()));
	    				System.out.println("recvDate inside if loop:::"+recvDate);
	    	        }

	    		}
	    		catch(Exception e)
	    		{
	    			errString = itmDBAccessEJB.getErrorString("","VPCVRECV02" , "SYSTEM");
					break;

	    		}

	    		if(noCVrcvdStr.trim().length() <= 3)
	    		{
					sql= "SELECT COUNT(*) AS COUNT from MPREQ_CVRECD  WHERE  VAC_NO=? AND RECD_DATE=?" ;
					pstmt=conn.prepareStatement(sql);
					pstmt.setString(1, vacNo);
					pstmt.setTimestamp(2,recvDate);
					rs=pstmt.executeQuery();

					while(rs.next())
					{
						count = rs.getInt("COUNT");
					}
					System.out.println("count:::" + count);
					if (rs != null)
					{
						rs.close();
						rs = null;
					}
					if (pstmt != null)
					{
						pstmt.close();
						pstmt = null;
					}

					if(count == 0)
					{
						sql="";
						sql= "INSERT INTO MPREQ_CVRECD (VAC_NO,RECD_DATE,NO_CV_RECD) VALUES (?,?,?)";
						pstmt=conn.prepareStatement(sql);
						pstmt.setString(1,vacNo);
						pstmt.setTimestamp(2,recvDate);
						pstmt.setInt(3,noOfCVRcvd);
						int insertCnt = pstmt.executeUpdate();
						System.out.println("MPREQ_CVRECD Inserted Rows:::" + insertCnt);

					}
					else
					{
						sql="";
						sql="UPDATE  MPREQ_CVRECD  SET  NO_CV_RECD = ?  WHERE  VAC_NO=?";
						pstmt=conn.prepareStatement(sql);
						pstmt.setInt(1,noOfCVRcvd);
						pstmt.setString(2, vacNo);

						int updCnt = pstmt.executeUpdate();
						System.out.println("No Of Record Updated in  MPREQ_CVRECD table[" + updCnt + "]");
					}

					System.out.println("Inside SUM:::");
					sql="";
					sql="SELECT sum(NO_CV_RECD) AS NO_CV_RECD FROM MPREQ_CVRECD WHERE VAC_NO=?";
					pstmt=conn.prepareStatement(sql);
					pstmt.setString(1, vacNo);
					rs=pstmt.executeQuery();
					while(rs.next())
					{
						sumNoCVRcvd = rs.getInt("NO_CV_RECD");
					}
					System.out.println("sumNoCVRcvd" + sumNoCVRcvd);
					if (rs != null)
					{
						rs.close();
						rs = null;
					}
					if (pstmt != null)
					{
						pstmt.close();
						pstmt = null;
					}
					
					//Modified by Suraj [05-FEB-2016][Start]
					/*sql="UPDATE MPREQ SET NO_CV_RECD = ?  WHERE  VAC_NO=? AND VAC_DATE=?";
					pstmt=conn.prepareStatement(sql);
					pstmt.setInt(1,sumNoCVRcvd);
					pstmt.setString(2, vacNo);
					pstmt.setTimestamp(3,recvDate);*/
					sql="UPDATE MPREQ SET NO_CV_RECD = ?  WHERE  VAC_NO=?";
					pstmt=conn.prepareStatement(sql);
					pstmt.setInt(1,sumNoCVRcvd);
					pstmt.setString(2, vacNo);
					//Modified by Suraj [05-FEB-2016][End]
					int updCnt1 = pstmt.executeUpdate();
					System.out.println("No Of Record Updated in  MPREQ table[" + updCnt1 + "]");
					if (updCnt1 > 0)
					{
						conn.commit();
					}
					

	    		}
	    		else
	    		{
	    			 errString = itmDBAccessEJB.getErrorString("","VPCVRECV01" , "SYSTEM");
					 break;
	    		}
	        }
			if (errString == null || errString.trim().length() == 0)
			{
				conn.commit();
				errString = itmDBAccessEJB.getErrorString("","VPCVRECV03" , "SYSTEM");
			}
			else
			{
				conn.rollback();
			}
		}


	    catch (Exception e)
	    {
	    	e.printStackTrace();
	    	try
			{
				conn.rollback();
			}
	    	catch (Exception d)
			{
				System.out.println("Exception::" + d.toString());
			}
			throw new ITMException(e);

	    }


	    finally
	    {
	    	System.out.println("Closing Connection....");
	    	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)
	    	{
	    		errString = e.getMessage();
	    		e.printStackTrace();
	    	}
	    }
    	return errString;
    }

}
//End By Juhi    08/12/2015  [A15BSUN007]   [End]
