
package ibase.webitm.ejb.adm;

import java.rmi.RemoteException;
import java.sql.*;
import java.text.SimpleDateFormat;

import org.w3c.dom.*;
import ibase.webitm.ejb.*;
import ibase.webitm.utility.ITMException;
import ibase.utility.E12GenericUtility;
import ibase.system.config.*;
import javax.naming.InitialContext;
import java.util.*;

@javax.ejb.Stateless

public class EmpCompletePrs extends ValidatorEJB implements EmpCompletePrsLocal, EmpCompletePrsRemote 
{	
	public String preSave()throws RemoteException,ITMException
	{
		return "";
	}

	public String preSave( String domString, String editFlag, String xtraParams, Connection conn ) throws RemoteException,ITMException
	{
		String retString = "";
		String objName = "";
		String empCode = "";
		java.util.Date dateJoin = null;
		String joinDate = "";
		String deptCode = "";
		String posCode = "";
		java.util.Date dateJoindb = null;
		String dateJoinOld = "";
		String deptCodeOld = "";
		String posCodeOld = "";
		
		String sql = "";
		PreparedStatement pstmt = null;
		ResultSet rs = null; 
		boolean isError = false;

		Document dom = null;		

		// Modified by Piyush on 08/12/2014 [To update user id in users table if changed CCF No. CQ14/CS1089 - A14GSUN004].Start
		String userIdDom = "";
		String userIdDB = "";
		ITMDBAccessLocal itmdbAccessLocal = null ;
		// Modified by Piyush on 08/12/2014 [To update user id in users table if changed CCF No. CQ14/CS1089 - A14GSUN004].End

		try
		{

			// Modified by Piyush on 08/12/2014 [To update user id in users table if changed CCF No. CQ14/CS1089 - A14GSUN004].Start
			AppConnectParm appConnect = new AppConnectParm();
			Properties p = appConnect.getProperty();
			InitialContext ctx = new InitialContext(p);
			itmdbAccessLocal = (ITMDBAccessLocal)ctx.lookup("ibase/ITMDBAccessEJB/local");
			// Modified by Piyush on 08/12/2014 [To update user id in users table if changed CCF No. CQ14/CS1089 - A14GSUN004].End

			conn.setAutoCommit( false );

			E12GenericUtility genericUtility = new E12GenericUtility();
			dom = genericUtility.parseString(domString);
			
			objName  = getObjNameFromDom( dom, "objName");
			System.out.println("objName["+objName+"]");
			
			String userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			String chgTerm = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "termId");
			
			System.out.println("domString EmpWorkInfoPrs ["+domString+"]");		
			
			SimpleDateFormat sdf = new SimpleDateFormat(getApplDateFormat());
			
			empCode =  checkNull(genericUtility.getColumnValue("emp_code", dom));
			posCode =  checkNull(genericUtility.getColumnValue("pos_code", dom));
			deptCode =  checkNull(genericUtility.getColumnValue("dept_code", dom));
			joinDate =  checkNull(genericUtility.getColumnValue("date_join", dom));

			// Modified by Piyush on 08/12/2014 [To update user id in users table if changed CCF No. CQ14/CS1089 - A14GSUN004]
			userIdDom =  checkNull(genericUtility.getColumnValue("user_id", dom));

			System.out.println("empCode:::::::: ["+empCode+"]");	
			System.out.println("posCode:::::::: ["+posCode+"]");	
			System.out.println("deptCode:::::::: ["+deptCode+"]");	
			System.out.println("joinDate:::::::: ["+joinDate+"]");	
			
			if(joinDate != null && joinDate.length() > 0)
			{
			dateJoin =  sdf.parse(joinDate);
			}
			System.out.println("dateJoin:::::::: ["+dateJoin+"]");	
			
			// Modified by Piyush on 08/12/2014 [Added user id to update user id in users table if changed CCF No. CQ14/CS1089 - A14GSUN004]
			//sql = "SELECT DEPT_CODE , POS_CODE , DATE_JOIN FROM EMPLOYEE WHERE EMP_CODE = ?";
			sql = "SELECT DEPT_CODE , POS_CODE , DATE_JOIN , USER_ID FROM EMPLOYEE WHERE EMP_CODE = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,empCode);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				deptCodeOld = checkNull(rs.getString("DEPT_CODE"));
				posCodeOld = checkNull(rs.getString("POS_CODE"));
				dateJoindb = rs.getDate("DATE_JOIN");
				// Modified by Piyush on 08/12/2014 [Added user id to update user id in users table if changed CCF No. CQ14/CS1089 - A14GSUN004]
				userIdDB = checkNull(rs.getString("USER_ID"));
			}
			if( rs != null)
			{
				rs.close();
				rs = null;
			}
			if( pstmt != null)
			{
				pstmt.close();
				pstmt = null;
			}

			// Modified by Piyush on 08/12/2014 [To update user id in users table if changed CCF No. CQ14/CS1089 - A14GSUN004].Start
			System.out.println("userIdDom:::::::: ["+userIdDom+"]");	
			System.out.println("userIdDB:::::::: ["+userIdDB+"]");	
			if (!userIdDom.equals(userIdDB))
			{
				int usrCnt = 0;
				sql = "SELECT COUNT(1) AS USER_CNT FROM USERS WHERE EMP_CODE = ?";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1,empCode);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					usrCnt = rs.getInt("USER_CNT");
				}
				if( rs != null)
				{
					rs.close();
					rs = null;
				}
				if( pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
				if (usrCnt > 0)
				{
					int usrUpdateCnt = 0;
					sql = "UPDATE USERS SET USER_ID = ? WHERE EMP_CODE = ?";
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1,userIdDom);
					pstmt.setString(2,empCode);
					usrUpdateCnt = pstmt.executeUpdate();
					if( pstmt != null)
					{
						pstmt.close();
						pstmt = null;
					}
					if (usrUpdateCnt != usrCnt)
					{
						retString = itmdbAccessLocal.getErrorString("","VTEMPUID01","");
						return retString;		
					}
				}
			}
			// Modified by Piyush on 08/12/2014 [To update user id in users table if changed CCF No. CQ14/CS1089 - A14GSUN004].End

			System.out.println("deptCodeOld:::::::: ["+deptCodeOld+"]");	
			System.out.println("posCodeOld:::::::: ["+posCodeOld+"]");		
			System.out.println("dateJoindb:::::::: ["+dateJoindb+"]");	
			
			if(dateJoindb != null )
			{
			dateJoinOld = sdf.format(dateJoindb);
			}
			System.out.println("dateJoinOld:::::::: ["+dateJoinOld+"]");	
			
			// Modified on 11/08/2016 [To resolve bug of position code not getting updated in case of made blank in edit mode]
			// if((posCode != null && posCode.length() > 0 ) && dateJoindb != null)
			if(dateJoindb != null && ((posCode != null && posCode.length() > 0 ) || (posCodeOld != null && posCodeOld.length() > 0 )))
			{
				AdmCommon ad = new AdmCommon();
				retString = ad.updateOrgStructure( domString,  empCode,  posCode,  deptCode, dateJoin, posCodeOld, deptCodeOld,  dateJoinOld, userId, chgTerm,  "EMPMST", conn ) ;
			}
		}
		catch(Exception e)
		{
			System.out.println("Exception :EmpCompletePrs : :==>\n"+e.getMessage());
			e.printStackTrace();
			isError = true;
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if( conn != null )
				{
					if (rs != null)
					{
						rs.close();
						rs = null;
					}
					if(pstmt != null)
					{
						pstmt.close();
						pstmt = null;
					}
					if( conn != null )
					{
						if( isError )
						{
							conn.rollback();
						}
					}
				}
			}
			catch(Exception e)
			{
				System.out.println("Exception :EmpCompletePrs : :==>\n"+e.getMessage());
				try
				{
					System.out.println("Before rollback");
					conn.rollback();
				}
			
				catch(SQLException sqle)
				{
                    System.out.println(sqle);
				}
				throw new ITMException(e);
			
			}
		}
		System.out.println("Return string :"+retString);
		return retString;		
	}

	private String getObjNameFromDom( Document dom, String attribute ) throws RemoteException,ITMException
	{
		String objName = "";
		try
		{
			NodeList detailList = null;
			Node currDetail = null,reqDetail = null;			
			int	detailListLength = 0;

			detailList = dom.getElementsByTagName("Detail1");
			detailListLength = detailList.getLength();
			for (int ctr = 0;ctr < detailListLength;ctr++)
			{
				currDetail = detailList.item(ctr);
				objName = currDetail.getAttributes().getNamedItem(attribute).getNodeValue();
						
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return objName;
	}

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