package ibase.utility.training;

//package ibase.webitm.ejb.wsfa.masters;

import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
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.CommonConstants;
import ibase.utility.E12GenericUtility;
import ibase.utility.GenericUtility;
import ibase.webitm.ejb.DBAccessEJB;
import ibase.webitm.ejb.ITMDBAccessEJB;
import ibase.webitm.ejb.ValidatorEJB;
import ibase.webitm.utility.ITMException;

@Stateless
public class UserTasks extends ValidatorEJB {
	
	protected static String database = CommonConstants.DB_NAME;
	
	
	@Override
	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 {
			BaseLogger.log("3",null,null,"xmlString:::" + xmlString);

			if (xmlString != null && xmlString.length() != 0) {
				dom = genericUtility.parseString(xmlString);
			}
			if (xmlString1 != null && xmlString1.length() != 0) {
				dom1 = genericUtility.parseString(xmlString1);
			}
			if (xmlString2 != null && xmlString2.length() != 0) {
				dom2 = genericUtility.parseString(xmlString2);
			}
			errString = wfValData(dom, dom1, dom2, objContext, editFlag, xtraParams);
		} catch (Exception e) {
			BaseLogger.log("3",null,null,"Exception : HealthProfile : wfValData(String xmlString) : ==>\n " + e.getMessage());
		}
		return errString;
	}

	@Override
	public String wfValData(Document dom, Document dom1, Document dom2, String objContext, String editFlag,
			String xtraParams) throws RemoteException, ITMException {
		Connection conn = null;
		conn = getConnection();
		PreparedStatement pst = null;
		ResultSet rs = null;
		
		GenericUtility genericUtility = GenericUtility.getInstance();
		E12GenericUtility utility = new E12GenericUtility();
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();

		
		BaseLogger.log("3",null,null,"wfValData.....called.[HealthProfile]");
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		String childNodeName = null;
		 
		String columnValue = "";
		int ctr = 0, currentFormNo = 0, childNodeListLength = 0, cnt = 0;
		String errString = "", errCode = "", userId = "";
		String hrProfile = "", descr = "", shortDescr = "", profType = "", mesuremType = "", recordfreq = "";
		String msrType = "";
		try {

			userId = getValueFromXTRA_PARAMS(xtraParams, "loginCode");
			if (objContext != null && objContext.trim().length() > 0) {
				currentFormNo = Integer.parseInt(objContext);
			}
			BaseLogger.log("3",null,null,"wdom:::::::::: : " + genericUtility.serializeDom(dom));
			BaseLogger.log("3",null,null,"wdom11111111111111:::::::::: : " + genericUtility.serializeDom(dom1));
			BaseLogger.log("3",null,null,"wdom222222222222222:::::::::: : " + genericUtility.serializeDom(dom2));
			switch (currentFormNo) {
			case 1:// First Form
				parentNodeList = dom.getElementsByTagName("Detail" + currentFormNo);
				parentNode = parentNodeList.item(0);
				childNodeList = parentNode.getChildNodes();
				childNodeListLength = childNodeList.getLength();
				BaseLogger.log("3",null,null,"child node list length=" + childNodeListLength);
				for (ctr = 0; ctr < childNodeListLength; ctr++)
				{
					childNode = childNodeList.item(ctr);
					childNodeName = childNode.getNodeName();
					BaseLogger.log("3",null,null,"idchildNodeName.editFlag." + childNodeName + ".." + editFlag);

//					if (childNodeName.equalsIgnoreCase("user_id")) 
//					{
//						BaseLogger.log("3",null,null,"--gsb-- FirstChild::" + childNode.getFirstChild());
//						if (childNode.getFirstChild() == null) 
//						{
//							errString = getErrorString("user", "NUUSERID", userId);
//						}
//						if (childNode.getFirstChild() != null) 
//						{
//							columnValue = checkNull(childNode.getFirstChild().getNodeValue());
//							BaseLogger.log("3",null,null,"--gsb-- columnValue::" + columnValue);
//							if (columnValue.length() == 0)
//							{
//								errString = getErrorString("user", "NUUSERID", userId);
//							}
//						}
//					}
					
				 if (childNodeName.equalsIgnoreCase("task_descr")) 
					{
						BaseLogger.log("3",null,null,"--gsb-- FirstChild::" + childNode.getFirstChild());
						if (childNode.getFirstChild() == null) {
							errString = getErrorString("descr", "NULUSRDESC", userId);
						}
						if (childNode.getFirstChild() != null) {
							columnValue = checkNull(childNode.getFirstChild().getNodeValue());
							BaseLogger.log("3",null,null,"----gsb--- columnValue::" + columnValue);
							if (columnValue.length() == 0) {
								errString = getErrorString("descr", "NULUSRDESC", userId);
							}
						}
						
						
					}
					else if (childNodeName.equalsIgnoreCase("user_id__assigned"))
					{
						BaseLogger.log("3",null,null,"--gsb-- FirstChild::" + childNode.getFirstChild());
						if (childNode.getFirstChild() == null) 
						{
							errString = getErrorString("useridass", "NULUSRIDAS", userId);
						}
						else 
                        {
                            int objCount = 0;
                            String usrAssign = E12GenericUtility.checkNull( utility.getColumnValue( "user_id__assigned", dom ) );
                            /*
                            if(!usrAssign.startsWith("w_"))
                            {
                                System.out.println("21042022-01 user assign :::["+usrAssign+"]");
                                usrAssign = "w_"+usrAssign;
                            }
                            */
                           // usrAssign = childNode.getFirstChild().getNodeValue().trim();
                            System.out.println("gsb databasename::"+database);
                            System.out.println("21042022-02 object name :::["+usrAssign+"]");
                            String objSQL = "SELECT COUNT(*) AS COUNT FROM USERS WHERE CODE = '"+usrAssign+"'";

                            pst = conn.prepareStatement(objSQL);
                            
                           // pst.setString(1, usrAssign);
                            rs = pst.executeQuery();
                           
                            if(rs.next())
                            {
                            	System.out.println("-----------------gsb------------IF Condition.................");
                            	objCount = rs.getInt("COUNT"); 
                            	System.out.println("gsb %% objCount::"+objCount);
                                
                            }
                            if(rs != null)
    						{
                            	rs.close();
                            	rs = null;
    						}
    						if(pst != null)
    						{
    							pst.close();
    							pst = null;
    						}
                            
                            if(objCount == 0)
                            {
                            	
                            	//System.out.println("count::"+objCount);
                                //System.out.println("Invalid User Assigned :::["+objCount+"]");
                                errString = itmDBAccessEJB.getErrorString("user_id__assigned","USRASSIGN",userId,"",conn);
                                break;
                            }
                          
                        }
						if (childNode.getFirstChild() != null) 
						{
							columnValue = checkNull(childNode.getFirstChild().getNodeValue());
							BaseLogger.log("3",null,null,"----gsb--- columnValue::" + columnValue);
							if (columnValue.length() == 0) 
							{
								errString = getErrorString("descr", "NULUSRIDAS", userId);
							}
						}
					}

				}
				break;
			}
		}
		/*
		 * case 2: // Second Form 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(); cnt = 0;
		 * BaseLogger.log("3",null,null,"idchildNodeName.editFlag." + childNodeName + ".." +
		 * editFlag + "Count is::[ " + cnt + " ]"); if
		 * (childNodeName.equalsIgnoreCase("msr_type")) { mesuremType =
		 * E12GenericUtility.checkNull(genericUtility.getColumnValue("msr_type", dom));
		 * if (mesuremType.length() == 0) { errCode = "VMMTCNB"; errString =
		 * getErrorString("msr_type", errCode, userId); break; } } } break; }// End
		 * Switch } // End Try
		 * 
		 */

		catch (Exception e) {
			BaseLogger.log("3",null,null,"Exception ::" + e);
			e.printStackTrace();
			errString = e.getMessage();
		} finally {
			try {
				if (conn != null) {
					conn.close();
					conn = null;
				}
			
			} catch (Exception d) {
				d.printStackTrace();
			}
		}
		BaseLogger.log("3",null,null,"ErrString ::" + errString);
		return errString;

	}

	@Override
	public String itemChanged(String xmlString, String xmlString1, String xmlString2, String objContext,
			String currentColumn, String editFlag, String xtraParams) throws RemoteException, ITMException {
		
		GenericUtility genericUtility = GenericUtility.getInstance();
		E12GenericUtility utility = new E12GenericUtility();
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();

		
		Document dom1 = null;
		Document dom = null;
		Document dom2 = null;
		String valueXmlString = "";

		try {
			if (xmlString != null && xmlString.trim().length() != 0) {
				BaseLogger.log("3",null,null,"xmlString>>>>" + xmlString);
				dom = genericUtility.parseString(xmlString);
			}
			if (xmlString1 != null && xmlString1.trim().length() != 0) {
				BaseLogger.log("3",null,null,"xmlString1>>>>" + xmlString1);
				dom1 = genericUtility.parseString(xmlString1);
			}
			if (xmlString2 != null && xmlString2.trim().length() != 0) {
				BaseLogger.log("3",null,null,"xmlString2>>>>" + xmlString2);
				dom2 = genericUtility.parseString(xmlString2);
				BaseLogger.log("3",null,null,"dom2:::-" + genericUtility.serializeDom(dom2));
			}
			valueXmlString = itemChanged(dom, dom1, dom2, objContext, currentColumn, editFlag, xtraParams);
		} catch (Exception e) {
			BaseLogger.log("3",null,null,"Exception :HealthProfile:itemChanged::::" + e.getMessage() + ":");
			e.printStackTrace();
		}
		BaseLogger.log("3",null,null,"returning from HealthProfile:itemChanged itemChanged");

		return valueXmlString;
	}

	@Override
	public String itemChanged(Document dom, Document dom1, Document dom2, String objContext, String currentColumn,
			String editFlag, String xtraParams) throws RemoteException, ITMException {
		
		Connection conn = null;
		conn = getConnection();
		PreparedStatement ppstmt = null;
		ResultSet rs = null;
		
		GenericUtility genericUtility = GenericUtility.getInstance();

		BaseLogger.log("3",null,null,"Itemchanged Called[HealthProfile]-------");
		StringBuffer valueXmlString = new StringBuffer();
		int currentFormNo = 0;
		String userId = "";
		String empName ="";
		String thGroup = "";
		
		Statement pstmt = null;
		ResultSet rSet = null;
		
		String chgDate = "", chgUser = "", chgTerm = "", addDate = "", addUser = "", addTerm = "";
		SimpleDateFormat sdf;
		Timestamp timestamp;
		try {

			BaseLogger.log("3",null,null,"dom:::::::::: : " + genericUtility.serializeDom(dom));
			BaseLogger.log("3",null,null,"dom11111111111111:::::::::: : " + genericUtility.serializeDom(dom1));
			BaseLogger.log("3",null,null,"dom222222222222222:::::::::: : " + genericUtility.serializeDom(dom2));
			sdf = new SimpleDateFormat(genericUtility.getApplDateFormat());
			//------------------------------------------
			String loginEmpCode = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginEmpCode");
			
			//--------------------------------------------------------
			timestamp = new Timestamp(System.currentTimeMillis());
			chgDate = (sdf.format(timestamp).toString()).trim();
			chgUser = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginEmpCode");
			chgTerm = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "chgTerm");
			BaseLogger.log("3",null,null,"Change Date :::-[" + chgDate + "]\n Change User:::-[" + chgUser
					+ "] \n Change Term:::-[" + chgTerm + "]");
			addDate = chgDate;
			addUser = chgUser;
			addTerm = chgTerm;
			if (objContext != null && objContext.trim().length() > 0)
				currentFormNo = Integer.parseInt(objContext);
			BaseLogger.log("3",null,null,"current form no: " + currentFormNo);
			currentColumn = currentColumn == null ? "" : currentColumn.trim();
			BaseLogger.log("3",null,null,"currentColumn : " + currentColumn);
			valueXmlString = new StringBuffer("<?xml version=\"1.0\"?><Root><header><editFlag>");
			valueXmlString.append(editFlag).append("</editFlag></header>");
			switch (currentFormNo) {
			case 1:// first From
				valueXmlString.append("<Detail1>");
				
				//------------------------------------------------------------------------
				if ("itm_default".equalsIgnoreCase(currentColumn)) 
				{	
					//it is used to fetch the name of user who loged in proteus vision
					
					try {
						//--------------------------------------------------------------------
						//String getGradeCodeSql = "SELECT (UPPER (EMP_FNAME )|| '  ' || UPPER(EMP_MNAME) || '  ' || UPPER(EMP_LNAME) )AS EMP_NAME FROM USERS WHERE EMP_CODE = ?";
						String getGradeCodeSql =  "SELECT NAME FROM USERS WHERE EMP_CODE=?";
						ppstmt = conn.prepareStatement(getGradeCodeSql);

						ppstmt.setString(1,loginEmpCode);
						rSet = ppstmt.executeQuery();
						 
						
						if( rSet.next())
						{
							empName =rSet.getString("NAME");
							System.out.println("Name of empNameinfo "+empName);
							System.out.println("Name of usersid");
						}
						if(rSet != null)
						{
							rSet.close();
							rSet = null;
						}
						if(ppstmt != null)
						{
							ppstmt.close();
							ppstmt = null;
						}
						
						
						}catch(Exception e) {
							System.out.println("@@@@username:"+e.getMessage());
							e.printStackTrace();
							
						}
					System.out.println("@@@@ loginEmpCode ::"+loginEmpCode);
					userId = genericUtility.getValueFromXTRA_PARAMS( xtraParams, "loginEmpCode" );
					
					System.out.println("UserIdInfo:"+userId);
					
					//SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
					SimpleDateFormat formatter = new SimpleDateFormat(genericUtility.getApplDateFormat()); 
					Date dte = new Date();
					String currentDate = "";
					BaseLogger.log("3",null,null,"current Date::" + dte);
					try 
					{
						currentDate = formatter.format(dte);
						BaseLogger.log("3",null,null,"String current Date::" + currentDate);
					} 
					catch (Exception ae) {
					}
					
					//it is used to fetch the userid who already login 
//					valueXmlString.append( "<user_id>" ).append( userId ).append( "</user_id>\r\n" );
					valueXmlString.append( "<user_id><![CDATA[" ).append( userId ).append( "]]></user_id>" );
					
					
					valueXmlString.append("<tran_date>").append("<![CDATA[" + currentDate + "]]>").append("</tran_date>");
					valueXmlString.append("<status_date>").append("<![CDATA[" + currentDate + "]]>").append("</status_date>");
					//------------------------------------------------------------------------
					
				
					//it is used to fetch the of user who login 
					//valueXmlString.append("<users_name><![CDATA[").append(empName).append("]]></users_name>");
					//valueXmlString.append( "<users_name><![CDATA[" ).append( empName ).append( "]]></users_name>\r\n" );
					System.out.println("gsb valueXmlString::"+valueXmlString);
					
					
					//-----------------------------------------------------------------------
				 } 
				 
				//it is used to fetch thename of the user after clicking on the name of pophelp the name is fetch which you selected in pophelp
				else if( "user_id__assigned".equalsIgnoreCase(currentColumn) )
				{
					try {
					//valueXmlString = new StringBuffer("<?xml version=\"1.0\"?><Root><header><editFlag>");
					//valueXmlString.append(editFlag).append("</editFlag></header>");
					//valueXmlString.append("<Detail1>");
						
						
//						// Using New method for retrieving data from database ---Starts
//							
//						DBAccessEJB dbAccessEJB = new DBAccessEJB();
//						try {
//						                                                messageFromBatchLoad = dbAccessEJB.getDBColumnValue("BATCHLOAD", "ERROR_MSG", "BATCH_ID  = '"+batchId+"'" + "AND ERROR_MSG IS NOT NULL", userInfo.getTransDB());
//						                                            } 
//						// Using New method for retrieving data from database ---End
//					 
					String code = genericUtility.getColumnValue("user_id__assigned",dom);
					System.out.println("thGroup ["+thGroup+"]");
					 
					String sql = "SELECT NAME FROM USERS WHERE CODE='"+code+"'";
					System.out.println("thGroup sql["+sql+"]");
					pstmt = conn.createStatement();
					rs = pstmt.executeQuery( sql );
					System.out.println("sqlQuery:"+rs);
					String Name = "";
					if( rs.next() )
					{
						
						Name=rs.getString("NAME") != null ? rs.getString("NAME").trim() : "" ;
			
						//valueXmlString.append("<users_name_1>").append( Name ).append("</users_name_1>");
						
						System.out.println("Triuser1"+Name);
					}
					 
					if(rs != null)
					{
						rs.close();
						rs = null;
					}
					if(pstmt != null)
					{
						pstmt.close();
						pstmt = null;
					}
					
					
					valueXmlString.append("<users_name><![CDATA[" ).append( Name ).append( "]]></users_name>\r\n" );
					
					//valueXmlString.append("</Detail1></Root>");
					}catch(Exception e)
					{
						System.out.println("Hello");
						e.printStackTrace();
					}
				}
				//--------------------------Changes done by amols----------------------------------------------------
				
				else if ("task_code".equalsIgnoreCase(currentColumn)) {
				    System.out.println("itemchange gsb1 : task_code");
				    try {
				        String task_code_value = genericUtility.getColumnValue("task_code", dom);
				        BaseLogger.log("3", null, null, "Value of task_code" + task_code_value);

				        String sqlquery = "SELECT EXP_TAT FROM TASK_MST WHERE TASK_CODE='" + task_code_value + "'";
				        pstmt = conn.createStatement();
				        rs = pstmt.executeQuery(sqlquery);
				        String EXP_TAT_Value = "";

				        if (rs.next()) {
				            EXP_TAT_Value = rs.getString("EXP_TAT") != null ? rs.getString("EXP_TAT").trim() : "";
				            System.out.println("ValueOfExpTAT" + EXP_TAT_Value);
				        }
				        
				        if (rs != null) {
				            rs.close();
				            rs = null;
				        }
				        if (pstmt != null) {
				            pstmt.close();
				            pstmt = null;
				        }

				        String updatedDateString;

				        if (EXP_TAT_Value != null && !EXP_TAT_Value.isEmpty()) {
				            int expTatIntValue = Integer.parseInt(EXP_TAT_Value);
				            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(genericUtility.getApplDateFormat());
				            LocalDate currentDate = LocalDate.now();
				            LocalDate updatedDate = currentDate.plusDays(expTatIntValue);
				            updatedDateString = formatter.format(updatedDate);
				           
				        } 
				        else
				        {
				            // If EXP_TAT is null or empty, set updatedDate to the current date
				            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(genericUtility.getApplDateFormat());
				            LocalDate currentDate = LocalDate.now();
				            updatedDateString = formatter.format(currentDate);
					        System.out.println("updatedDate gsb of else case " + updatedDateString);

				        }

				        System.out.println("updatedDate gsb " + updatedDateString);
				        valueXmlString.append("<exp_compl_date><![CDATA[").append(updatedDateString).append("]]></exp_compl_date>\r\n");

				    } catch (Exception e) {
				        System.out.println("HELLO1");
				        e.printStackTrace();
				    }
				}

			//////////////////////////////////////////////////////6 nov	
				//it is used for edit purpose because you use compute for column user_assigned_name in free 
				else if (currentColumn.trim().equalsIgnoreCase("itm_defaultedit")) 
				{
					try {
					String code = genericUtility.getColumnValue("user_id__assigned",dom);
					String sql = "SELECT NAME FROM USERS WHERE CODE='"+code+"'";
					System.out.println("thGroup sql["+sql+"]");
					pstmt = conn.createStatement();
					rs = pstmt.executeQuery( sql );
					System.out.println("sqlQuery:"+rs);
					String Name = "";
					if( rs.next() )
					{
						
						Name=rs.getString("NAME") != null ? rs.getString("NAME").trim() : "" ;
						//fldValue = checkNull(rs.getString("CODE"));
			
						//valueXmlString.append("<users_name_1>").append( Name ).append("</users_name_1>");
						
						
						
						System.out.println("Triuser1"+Name);
					}
					 
					if(rs != null)
					{
						rs.close();
						rs = null;
					}
					if(pstmt != null)
					{
						pstmt.close();
						pstmt = null;
					}
					
					//valueXmlString.append("<chg_date>").append("<![CDATA[" + chgDate + "]]>").append("</chg_date>");
					valueXmlString.append("<users_name><![CDATA[" ).append( Name ).append( "]]></users_name>\r\n" );
					
					System.out.println("gsb code::"+code);
					}catch(Exception e) {
						System.out.println("@@@gsbHello");
						e.printStackTrace();
					}
					
				}
				valueXmlString.append("</Detail1>");
				break;

			/*
			 * case 2:// second From
			 * 
			 * BaseLogger.log("3",null,null,"case2>>>>>>>>"); String detHrProf =
			 * genericUtility.getColumnValue("hr_profile", dom); String seqNO =
			 * genericUtility.getColumnValue("seq_no", dom);
			 * BaseLogger.log("3",null,null,"Detail hr profile ::::-[" + detHrProf + "]" +
			 * "Sequence no :::-[" + seqNO + "]"); valueXmlString.append("<Detail2>\r\n");
			 * if (currentColumn.trim().equalsIgnoreCase(("itm_default"))) { parentNodeList
			 * = dom2.getElementsByTagName("Detail2"); childNode =
			 * parentNodeList.item(parentNodeList.getLength() - 1);
			 * BaseLogger.log("3",null,null,"Child Node :::=[" + childNode.toString() + "]"); if
			 * (childNode != null) { String childNodeName = childNode.getNodeName(); if
			 * ("Detail2".equalsIgnoreCase(childNodeName)) { String domId =
			 * childNode.getAttributes().getNamedItem("domID").getNodeValue();
			 * BaseLogger.log("3",null,null,"Dom Id ::::-[" + domId + "]");
			 * //valueXmlString.append("<seq_no>").append(Integer.parseInt(domId)).append(
			 * "</seq_no>\r\n"); } } }
			 * 
			 * 
			 * valueXmlString.append("</Detail2>\r\n"); break;
			 */

			}// End Switch
			valueXmlString.append("</Root>");
		} // End Try

		catch (Exception e) {
			e.printStackTrace();
			BaseLogger.log("3",null,null,"Exception ::" + e.getMessage());
			throw new ITMException(e);
		} finally {
			try {
				if (conn != null) {
					conn.close();
					conn = null;
				}
				
			} catch (Exception d) {
				d.printStackTrace();
			}
		}
		BaseLogger.log("3",null,null,"\n HealthProfile:ValueXmlString :" + valueXmlString + ":*******");
		return valueXmlString.toString();

	}

	public static String checkNull(String input) {
		if (input == null || "null".equalsIgnoreCase(input) || "undefined".equalsIgnoreCase(input)) {
			input = "";
		}
		return input.trim();
	}
}