package ibase.webitm.ejb.sys;

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

import javax.ejb.Stateless;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import ibase.system.config.ConnDriver;
import ibase.utility.BaseLogger;
import ibase.utility.E12GenericUtility;
import ibase.webitm.ejb.ITMDBAccessEJB;
import ibase.webitm.ejb.ValidatorEJB;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;

public class DSAApplicantNewLead extends ValidatorEJB
{
	E12GenericUtility genericUtility = new E12GenericUtility();
	public String wfValData(String xmlString, String xmlString1, String xmlString2, String objContext, String editFlag,
			String xtraParams) throws RemoteException, ITMException {
		System.out.println("wfValData method called ==>04aug");

		Document dom = null;
		Document dom1 = null;
		Document dom2 = null;
		String errString = null;
		
		System.out.println("xmlString[" + xmlString + "]");
		System.out.println("xmlString1[" + xmlString1 + "]");
		System.out.println("xmlString2[" + xmlString2 + "]");

		try {

			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) // Catch any other exception
		{
			System.out.println("Exception: SfaTime: wfValData(String xmlString): " + e.getMessage() + ":");
			errString = genericUtility.createErrorString(e);
			e.printStackTrace();
		}
		System.out.println("Returning from SfaTime wfValData");
		return (errString);
	}
		
	@Override
	public String wfValData(Document dom, Document dom1, Document dom2, String objContext, String editFlag,
			String xtraParams) throws RemoteException, ITMException {
		System.out.println("Inside the  validation mehtod===>");
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		Connection conn = null;
		String childNodeName = null;
		String errorString = "";
		String userId = "";
		int ctr = 0;
		int currentFormNo = 0;
		int childNodeListLength = 0;

		try {
			conn = getConnection();
			userId = getValueFromXTRA_PARAMS(xtraParams, "loginEmpCode");
			BaseLogger.log("3", null, null, "userId : DOM :: [" + userId + "]");

			if (objContext != null && objContext.trim().length() > 0) {
				currentFormNo = Integer.parseInt(objContext);
			}
			parentNodeList = dom.getElementsByTagName("Detail" + currentFormNo);
			parentNode = parentNodeList.item(0);
			childNodeList = parentNode.getChildNodes();
			childNodeListLength = childNodeList.getLength();
			for (ctr = 0; ctr < childNodeListLength; ctr++) {
				childNode = childNodeList.item(ctr);
				childNodeName = childNode.getNodeName();
				switch (currentFormNo) 
				{
				case 1:
					BaseLogger.log("3", null, null, "Inside the validation");
					
					String allocatedTo = checkNull(genericUtility.getColumnValue("allocated_to", dom));
					BaseLogger.log("3", null, null, "AllocatedTo : DOM :: [" + allocatedTo + "]");

					

				}
			}
		} catch (Exception e) {
			BaseLogger.log("3", null, null, "MailingListPostSave : DOM :: In catch block");
		}
		finally {
	        if (conn != null) {
	            try {
	                conn.close();
	                conn =null;
	            } catch (SQLException e) {
	                e.printStackTrace();
	            }
	        }
	    }
		return errorString;
	}


	private String checkNull(String input) {
		if (input == null) {
			input = "";
		} else {
			input = input.trim();
		}
		return input;
	}
	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 errString = null;

		try {

			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);
			}
			// passing the dom to itemchanged method
			errString = itemChanged(dom, dom1, dom2, objContext, currentColumn, editFlag, xtraParams);
			System.out.println("ErrString :" + errString);
		} catch (Exception e) {
			System.out.println("Exception :SfaTime :itemChanged(String,String):" + e.getMessage() + ":");
			errString = genericUtility.createErrorString(e);
		}

		System.out.println("returning from SfaTime itemChanged");
		return errString;
	}

	@Override
	public String itemChanged(Document dom, Document dom1, Document dom2, String objContext, String currentColumn,
			String editFlag, String xtraParams) throws RemoteException, ITMException {
		System.out.println("Inside itemchange====>> 12 Oct-25");
		// Document headerDom = null;
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		StringBuffer valueXmlString = null;
		String name = "";
		String email_id = "";
		int currentFormNo = 0;
		String loginEmpCode = "" ,profildId="",reportTo="",reportToManager="",userId="",allocatedTo="",reportToSecond="",profileID="",empCode="";
		NodeList parentNodeList = null;
		Node parentNode = null;
		NodeList childNodeList = null;
		String loginCode = "",reportToEdit="";
		
		//for date-strt
		Date currentDate = new java.util.Date();
      //  valueXmlString.append("<tran_date >").append("<![CDATA[" + sdf1.format(currentDate) +"]]>").append("</tran_date>");

		//end

		ConnDriver connDriver = new ConnDriver();
		try {
			 userId = getValueFromXTRA_PARAMS(xtraParams, "loginCode");
			BaseLogger.log("3", null, null, " loginCode New==> " +userId);
//			
		   allocatedTo = checkNull(genericUtility.getColumnValue("allocated_to", dom));
 		   BaseLogger.log("3", null, null, "AllocatedTo : DOM :: [" + allocatedTo + "]");
           SimpleDateFormat sdf1 = new SimpleDateFormat(genericUtility.getApplDateFormat());


           //Upadet by Amol S on 31-Oct , get the connection with User--start 
			conn = connDriver.getConnectDB("Driver");
	       //Upadet by Amol S on 31-Oct , get the connection with User--End 

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

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

			switch (currentFormNo)

			{
			case 1:
				BaseLogger.log("3", getUserInfo(), null, "Inside Case1 Itemchanged Newchnge===>");
				parentNodeList = dom.getElementsByTagName("Detail1");
				parentNode = parentNodeList.item(0);
				childNodeList = parentNode.getChildNodes();
				valueXmlString.append("<Detail1>");
				
				
			//	String sql = " select report_to  from users where code = ? ";
				//Changes by Amol S on 12 Oct -25 --strt
				String sql = " select emp_code ,profile_id  from users where code = ? ";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, userId);
				rs = pstmt.executeQuery();

				if (rs.next()) {
					//reportTo = rs.getString("report_to"); //gagan get here 
					empCode = rs.getString("emp_code").trim(); 
					profileID = rs.getString("profile_id").trim(); 
					BaseLogger.log("3", null, null, " profileID==> " +profileID);


				}
				rs.close();
				pstmt.close();
				pstmt = null;
				rs = null;
				//Chnge by Amol S on 3rd Nov -strt to close the Driver conn -Start
				conn.close();
				//Chnge by Amol S on 3rd Nov -strt to close the Driver conn --End

				
				
				//first level 12-oct--start
				
				String sqlreport_to = " select report_to from employee where emp_code = ? ";
				//Added  on 03-nov to update the conn--strt
				conn = getConnection();
				//Added  on 03-nov to update the conn--strt

				pstmt = conn.prepareStatement(sqlreport_to);
				pstmt.setString(1, empCode);
				rs = pstmt.executeQuery();

				if (rs.next()) {
					reportTo = rs.getString("report_to").trim(); //gagan get here 

					BaseLogger.log("3", null, null, " reportTo=====> " +reportTo);


				}
				rs.close();
				pstmt.close();
				pstmt = null;
				rs = null;
				//end
				
				
				
				//added on 04-Aug  -strt
				 sql = " select  report_to  from employee where emp_code = ? ";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, empCode);
				rs = pstmt.executeQuery();

				if (rs.next()) {
					reportToManager = rs.getString("report_to").trim(); //ggaan get here
					BaseLogger.log("3", null, null, "Reporting manager::==>>" +reportToManager);

				}
				rs.close();
				pstmt.close();
				pstmt = null;
				rs = null;
				
				if("itm_default".equalsIgnoreCase(currentColumn.trim())){
					
					BaseLogger.log("3", null, null, " inside  itm default ");
					//NewAdd strt
					loginCode = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginCode");
					BaseLogger.log("3", getUserInfo(), null, "LoginCode::==> " + loginCode);

					valueXmlString.append("<add_user>").append("<![CDATA[" + loginCode + "]]>").append("</add_user>");
					valueXmlString.append("<chg_user>").append("<![CDATA[" + loginCode + "]]>").append("</chg_user>");
					//Added on 12-Oct-25  by Amol S
					if("DSA".equalsIgnoreCase(profileID.trim()))
					{
						BaseLogger.log("3", getUserInfo(), null, "Inside for DSA profile==>:: ");

						valueXmlString.append("<allocated_to protect='1' visible='0'>").append("<![CDATA[" + reportTo + "]]>").append("</allocated_to>");
				        valueXmlString.append("<tran_date protect='1' visible='0'>").append("<![CDATA[" + sdf1.format(currentDate) +"]]>").append("</tran_date>");
						//Made changes on 10-DEC by AJIT -- If user profile is DSA then set a status as Open
				        valueXmlString.append("<status protect='1' visible='0'>").append("<![CDATA[" + "O" + "]]>").append("</status>");
						valueXmlString.append("<status_date  protect='1' visible='0'>").append("<![CDATA[" + sdf1.format(currentDate) +"]]>").append("</status_date>");
						valueXmlString.append("<status_remarks protect='1' visible='0'>").append("<![CDATA[" + "" + "]]>").append("</status_remarks>");

						
					}
					//end
					//loginEmpCode = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginEmpCode");
					//	 userId = getValueFromXTRA_PARAMS(xtraParams, "loginCode");
					
					/*
					if ("ADMIN".equalsIgnoreCase(profildId))
					{
					BaseLogger.log("3", null, null, "Inside the method Adminnnnnn" +userId);

					valueXmlString.append("<allocated_to protect='1'>").append("<![CDATA[" + reportTo + "]]>").append("</allocated_to>");
					}
					*/
					
					if (userId.equalsIgnoreCase(reportToManager.trim())) 
					{
						BaseLogger.log("3", null, null, "Inside the if block " +reportTo);

						valueXmlString.append("<allocated_to protect='0'>").append("<![CDATA[" + reportTo + "]]>").append("</allocated_to>");

					}
			
					else
					{
					valueXmlString.append("<allocated_to protect='1'>").append("<![CDATA[" + reportTo + "]]>").append("</allocated_to>");
					}
					
					 }
				}
				
				if("itm_defaultedit".equalsIgnoreCase(currentColumn.trim())){
					BaseLogger.log("3", null, null, "itm_defaultedit default edit 12-OCT ");
					//Added on 04Aug-strt--for 3rd level manger --strt
				//	String sql = " select report_to  from users where code = ? ";
					String sql = " select report_to  from employee where emp_code = ? ";
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, allocatedTo);
					rs = pstmt.executeQuery();

					if (rs.next()) {
						 reportToEdit = rs.getString("report_to"); //gagan get here 
						BaseLogger.log("3", null, null, "reportToEdit:==>" + reportToEdit);

					}
					rs.close();
					pstmt.close();
					pstmt = null;
					rs = null;
					//Added on 04Aug-strt--for 3rd level manger --end
					
					//Added by Amol S on 12 -Oct -25 -strt
					if("DSA".equalsIgnoreCase(profileID.trim()))
					{
						
						BaseLogger.log("3", getUserInfo(), null, "Inside for DSA profile for edit case==> ");

						valueXmlString.append("<allocated_to protect='1'>").append("<![CDATA[" + reportTo + "]]>").append("</allocated_to>");
				        valueXmlString.append("<tran_date protect='1' visible='0' >").append("<![CDATA[" + sdf1.format(currentDate) +"]]>").append("</tran_date>");
				        valueXmlString.append("<status protect='1' visible='0'>").append("<![CDATA[" + "O" + "]]>").append("</status>");
						valueXmlString.append("<status_date protect='1' visible='0'>").append("<![CDATA[" + sdf1.format(currentDate) +"]]>").append("</status_date>");
						valueXmlString.append("<status_remarks protect='1' visible='0'>").append("<![CDATA[" + "" + "]]>").append("</status_remarks>");

					}
					
					//end
				
			     	//Added on 06Aug-strt--for 2nd level manger --strrt
					
					//if (userId.equalsIgnoreCase(reportTo))
					if (userId.equalsIgnoreCase(reportToEdit.trim()))
					{
						
						BaseLogger.log("3", null, null, "inside theitm_default reportToManager Today::==>" + reportToManager);
						valueXmlString.append("<allocated_to protect='0'>").append("<![CDATA[" + allocatedTo + "]]>").append("</allocated_to>");
							
					}
				//	(userId.equalsIgnoreCase(reportToManager)  ||userId.equalsIgnoreCase(reportToSecond))
					else
					{
					BaseLogger.log("3", null, null, "inside else of itm_defaultedit test ==>>> ==>"+userId);

					valueXmlString.append("<allocated_to protect='1'>").append("<![CDATA[" + allocatedTo + "]]>").append("</allocated_to>");
					}
					//End
				}
				valueXmlString.append("</Detail1>\r\n");

			valueXmlString.append("</Root>\r\n");
		} catch (Exception e) {
			System.out.println("Exception :SfaTime :itemChanged(Document,String):" + e.getMessage() + ":");
			e.printStackTrace();
		} finally {
			try {
				if (conn != null) {
					conn.close();
					conn = null;
				}
				if (rs != null) {
					rs.close();
					rs = null;
				}
				if (pstmt != null) {
					pstmt.close();
					pstmt = null;
				}
			} catch (Exception e) {
				System.out.println("Exception :SfaTime :Exception in SQL" + e.getMessage() + ":");
				e.printStackTrace();
			}
		}
		return valueXmlString.toString();
	}
}