package ibase.webitm.ejb.adm;

import ibase.utility.CommonConstants;
import java.sql.*;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import ibase.webitm.utility.TransIDGenerator;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.*;

/*
	Sudhir	 
*/ 

public class AdmCommon 
{
	public String getSiteEnv(String siteCode, String module, String levelType, String levelCode, String parName, Timestamp date, Connection conn) 
	{
		System.out.println("siteCode :"+siteCode+" module : "+module+" levelType  :"+levelType+"  levelCode  :"+levelCode+"  parName :"+parName+"  date :"+date );
		String parValue = "";
		String sql = "";
		
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try
		{
			sql = "SELECT PAR_VALUE "   
				+ "FROM SITE_ENV "
				+ "WHERE SITE_CODE	= 	'" + siteCode + "' "
				+ "AND MODULE_CODE	= 	'" + module + "' "
				+ "AND LEVEL_TYPE	= 	'" + levelType + "' "
				+ "AND LEVEL_CODE	= 	'" + levelCode + "' "
				+ "AND PAR_NAME		= 	'" + parName + "' "
				+ "AND EFF_DATE		<=	? " 
				+ "AND UPTO_DATE	>=	? ";
			System.out.println(">>>>>>>>>>>..  sql in getSiteEnv  "+sql);
			pstmt = conn.prepareStatement(sql);
			pstmt.setTimestamp(1, date);
			pstmt.setTimestamp(2, date);
			rs = pstmt.executeQuery();
			if (rs.next())
			{
				parValue = rs.getString(1);
				pstmt.close();
				rs.close();
			}
			else if(levelType.equalsIgnoreCase("X") && !module.equalsIgnoreCase("ADM"))  
			{
				pstmt.close();
				rs.close();
				sql = "SELECT PAR_VALUE "  
					+ "FROM SITE_ENV "
					+ "WHERE SITE_CODE	= 	'99999' "
					+ "AND MODULE_CODE	= 	'" + module + "' "
					+ "AND LEVEL_TYPE	= 	'" + levelType + "' "
					+ "AND LEVEL_CODE	= 	'" + levelCode + "' "
					+ "AND PAR_NAME		= 	'" + parName + "' "
					+ "AND EFF_DATE		<=	? "
					+ "AND UPTO_DATE	>=	? ";
				System.out.println(">>>>>>>>>>>..  sql in getSiteEnv else  "+sql);
				pstmt = conn.prepareStatement(sql);
				pstmt.setTimestamp(1, date);
				pstmt.setTimestamp(2, date);
				rs = pstmt.executeQuery();
				if (rs.next())
				{
					parValue = rs.getString(1);
				}
				else
				{
					parValue = "NULLFOUND";
				}
			}
			else
			{
				parValue = "NULLFOUND";
			}
			rs.close();
			pstmt.close();	
			if (parValue == null) parValue = "NULLFOUND"; //ADDED BY ALKA 25/07/07 TO AVOID NULLPOINTER EXCEPTION FROM WHERE THE METHOD IS CALLED.
		}
		catch (Exception e)
		{
//			System.out.println("Exception :ITMDBAccessEJB :getEvFin:" + e.getMessage() + ":"); //COMMENTED BY ALKA 24/07/07 AS WRONG METHOD NAME IS PRINTED IN THE SOP
			System.out.println("Exception :ITMDBAccessEJB :getSiteEnv:" + e.getMessage() + ":");
		}
//		System.out.println("Returning Value From getEnvFin() :: "+parValue);  //COMMENTED BY ALKA 24/07/07 AS WRONG METHOD NAME IS PRINTED IN THE SOP
		System.out.println("Returning Value From getSiteEnv() :: "+parValue);  
		return parValue;
	}
	public String getAdmEnv(String siteCode, String cadre, String grade, String envName, Timestamp date, Connection conn) 
	{
		String retValue = "";
		try
		{
			retValue = getSiteEnv(siteCode, "ADM", "G",  grade,  envName,  date,  conn);
			if(retValue.equals("NULLFOUND"))
			{
				retValue = getSiteEnv(siteCode, "ADM", "C",  cadre,  envName,  date,  conn);
				if(retValue.equals("NULLFOUND"))
				{
					retValue = getSiteEnv(siteCode, "ADM", "X", "ZZZZZ",  envName,  date,  conn);
					if(retValue.equals("NULLFOUND"))
					{
						retValue = getSiteEnv(siteCode, "ADM", "G",  grade,  envName,  date,  conn);
						if(retValue.equals("NULLFOUND"))
						{
							retValue = getSiteEnv(siteCode, "ADM", "C",  cadre,  envName,  date,  conn);
							if(retValue.equals("NULLFOUND"))
							{
								retValue = getSiteEnv(siteCode, "ADM", "X", "ZZZZZ",  envName,  date,  conn);
							}
						}
					}
				}
			}
		}
		catch (Exception e)
		{
			System.out.println("Exception :AdmCommon :getEnvFin:" + e.getMessage() + ":");
			e.printStackTrace();
		}
		System.out.println("Returning Value From getAdmEnv() :: "+retValue);  
		return retValue;
	}
	public String getEnv(String prdCode, String varName,Connection conn)
	{
		String retValue = "";
		String sql = "";
		Statement stmt = null;
		ResultSet rs = null;
		try
		{
			sql = "SELECT VAR_VALUE FROM PAYRPARM "  
			   	+ "WHERE PRD_CODE = '" + prdCode + "' AND VAR_NAME = '" + varName + "'";
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
			if (rs.next())
			{
				retValue = rs.getString(1);
			}
			else
			{
				retValue = "NULLFOUND";
			}
			rs.close();
			stmt.close();
		}
		catch (SQLException se)
		{
			System.out.println("Exception :ITMDBAccessEJB :getEnvFin:" + se.getMessage() + ":");
			se.printStackTrace();
		}
		catch (Exception e)
		{
			System.out.println("Exception :ITMDBAccessEJB :getEnvFin:" + e.getMessage() + ":");
			e.printStackTrace();
		}
	//	System.out.println("Returning Value From getEnvFin() :: "+retValue);  
		return retValue;
	}
	//Function empPrevRec(String empCode, String adCode, String effDate, Connection conn) added by Gulzar 15/01/07
	public boolean empPrevRec(String empCode, String adCode, String effDate, Connection conn) throws ITMException
	{
		boolean status = false;
		String updSql = "", relativeDate = "";
		int updCnt = 0;
		PreparedStatement pstmt = null;
		Statement stmt = null;
		ResultSet rs = null;
		try
		{
			conn.setAutoCommit(false);
			GenericUtility genericUtility = GenericUtility.getInstance();
			relativeDate = getRelativeDate(effDate,-1);
			System.out.println("relativeDate...::" + relativeDate);
			
			updSql = "UPDATE EMPLOYEE_AD SET EXP_DATE = ? " +
					" WHERE EMP_CODE = '"+empCode+"' AND " +
					" AD_CODE = '"+adCode+"' AND " +
					" EFF_DATE <= ? AND " +
					" EXP_DATE >= ? ";
			System.out.println("Update sql In [empPrevRec][updSql][1]........:: " + updSql);
			pstmt = conn.prepareStatement(updSql);
			pstmt.setTimestamp(1,java.sql.Timestamp.valueOf(genericUtility.getValidDateTimeString(relativeDate,genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat())));
			pstmt.setTimestamp(2,java.sql.Timestamp.valueOf(genericUtility.getValidDateTimeString(effDate,genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat())));
			pstmt.setTimestamp(3,java.sql.Timestamp.valueOf(genericUtility.getValidDateTimeString(effDate,genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat())));
			updCnt = pstmt.executeUpdate();
			if(updCnt > 0)
			{
				status = true;
				System.out.println("Updated Into EMPLOYEE_AD Sucessfully......! [updCnt] :: "+ updCnt);
			}
			else
			{
				System.out.println("No Updation into EMPLOYEE_AD......! [updCnt] :: "+ updCnt);
			}
		}
		catch (SQLException se)
		{
			System.out.println("Exception :AdmCommon :empPrevRec:" + se.getMessage() + ":");
			se.printStackTrace();
			try
			{
				conn.rollback();
			}
			catch(Exception se1){}
			throw new ITMException(se);
		}
		catch(Exception e)
		{
			System.out.println("Exception :[AdmCommon][function::empPrevRec()] :==>\n"+e.getMessage());
			e.printStackTrace();
			try
			{
				conn.rollback();
			}
			catch(Exception e1){}
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				System.out.println("Closing pstmt In [empPrevRec()]...............");
				if (pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
				if (stmt != null)
				{
					stmt.close();
					stmt = null;
				}
			}
			catch(Exception ex){}
		}
		return status;
	}
	//Function payarrToProcUpdation() Added by Gulzar 16/010/07
	public String payarrToProcUpdation(String periodFrom, String periodTo, String empCodeFr, String empCodeTo, String procType, String winName, String keyStr, String adCode, double amount, String effDate, String expDate, String xtraParams, Connection conn) throws ITMException
	{
		String errCode = "", sqlStr = "", keyString = "", adBasic = "", startPeriod = "";
		String sqlEmp = "", sqlPrd = "", voucherNo = "", tranID = "", sqlIns = "";
		String currEmpCode = "", currPeriod = "", userId = "";
		int count = 0, count1 = 0;
		Statement stmt = null, stmtEmp = null, stmtPrd = null, stmt1 = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null, rsEmp = null, rsPrd = null, rs1 = null;
		java.sql.Timestamp joinDate = null;
		
		try
		{
			GenericUtility genericUtility = GenericUtility.getInstance();
			userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"userId");
			conn.setAutoCommit(false);
			stmt = conn.createStatement();
			adBasic = getEnv("999999", "BASIC", conn);
			if (adBasic.equals("NULLFOUND"))
			{
				errCode = "VSENVAR1";
				return errCode;
			}
			sqlStr = "SELECT KEY_STRING FROM TRANSETUP WHERE UPPER(TRAN_WINDOW) = 'T_PAYARR_TO_PROC'";
			System.out.println("sqlStr In [payarrToProcUpdation][sqlStr][1]........:: " + sqlStr);
			rs = stmt.executeQuery(sqlStr);
			if (rs.next())
			{
				keyString = rs.getString("KEY_STRING");
			}
			System.out.println("keyString.....:: " + keyString);
			rs.close();
			rs = null;
			if (periodTo == null)
			{
				periodTo = "";
			}
			startPeriod = getEnv("999999", "START_PRD", conn);
			if (startPeriod.equals("NULLFOUND"))
			{
				errCode = "VSENVAR1";
				return errCode;
			}
			sqlStr = "SELECT COUNT(*) AS COUNT FROM PERIOD WHERE CODE = '"+startPeriod+"'";
			System.out.println("sqlStr In [payarrToProcUpdation][sqlStr][2]........:: " + sqlStr);
			rs = stmt.executeQuery(sqlStr);
			if (rs.next())
			{
				count = rs.getInt("COUNT");
			}
			else
			{
				errCode = "STARTPRD";
				return errCode;
			}
			rs.close();
			rs = null;
			stmt.close();
			stmt = null;
			sqlEmp = "SELECT EMP_CODE, DATE_JOIN FROM EMPLOYEE WHERE EMP_CODE >= '"+empCodeFr+"' AND EMP_CODE <= '"+empCodeTo+"'";
			System.out.println("sqlEmp In [payarrToProcUpdation][sqlEmp][3]........:: " + sqlEmp);
			stmtEmp = conn.createStatement();
			rsEmp = stmtEmp.executeQuery(sqlEmp);
			while (rsEmp.next())
			{
				currEmpCode = rsEmp.getString("EMP_CODE");
				joinDate	= rsEmp.getTimestamp("DATE_JOIN");
				sqlPrd = "SELECT CODE FROM PERIOD WHERE CODE >= '"+periodFrom+"' AND CODE >= '"+startPeriod+"'";
				System.out.println("sqlPrd In [payarrToProcUpdation][sqlPrd][4]........:: " + sqlPrd);
				stmtPrd = conn.createStatement();
				rsPrd = stmtPrd.executeQuery(sqlPrd);
				while (rsPrd.next())
				{
					currPeriod = rsPrd.getString("CODE");
					if (periodTo != null && periodTo.trim().length() > 0 && Integer.parseInt(currPeriod) > Integer.parseInt(periodTo))
					{
						break;
					}
					voucherNo = "";
					sqlStr = "SELECT VOUCHER_NO FROM PAYROLL WHERE PRD_CODE = '"+currPeriod+"' AND EMP_CODE = '"+currEmpCode+"' AND VOUCHER_NO <> 'PAYROLL'";
					System.out.println("sqlStr In [payarrToProcUpdation][sqlStr][5]........:: " + sqlStr);
					stmt = conn.createStatement();
					rs = stmt.executeQuery(sqlStr);
					if (rs.next())
					{
						voucherNo = rs.getString("VOUCHER_NO");
						if ((voucherNo != null && voucherNo.trim().length() > 0) || procType.equals("PY"))
						{
							sqlStr = "SELECT COUNT(*) AS COUNT FROM PAYARR_TO_PROC WHERE EMP_CODE = '"+currEmpCode+"'" +
									" AND PRD_CODE = '"+currPeriod+"' AND STATUS = 'U' AND PROC_TYPE = '"+procType+"'" ;
							System.out.println("sqlStr In [payarrToProcUpdation][sqlStr][6]........:: " + sqlStr);
							stmt1 = conn.createStatement();
							rs1 = stmt1.executeQuery(sqlStr);
							if (rs1.next())
							{
								count1 = rs1.getInt("COUNT");
							}
							rs1.close();
							rs1 = null;
							stmt1.close();
							stmt1 = null;
							System.out.println("COUNT(*) FROM PAYARR_TO_PROC.....::[count1]:: "+ count1);
							if (count1 == 0)
							{
								String XMLString = "<?xml version=\"1.0\"?>\r\n<Root>\r\n<header>"+
								"\r\n</header><Detail1></Detail1></Root>";
								CommonConstants.setIBASEHOME();
								TransIDGenerator tg = new TransIDGenerator(XMLString, userId, CommonConstants.DB_NAME);
								tranID = tg.generateTranSeqID("PAYARR", "tran_id", keyString, conn);
								System.out.println("Transaction Id Generated [tranID] :: "+tranID);
								if (tranID.equals("ERROR"))
								{
									errCode = "VTTRANID";
									break;
								}
								String status = "U";
								sqlIns = "INSERT INTO PAYARR_TO_PROC (TRAN_ID, EMP_CODE, PRD_CODE, STATUS, PROC_TYPE, CHG_DATE, CHG_USER, CHG_TERM) " +
										" VALUES(?,?,?,?,?,?,?,?)";
								System.out.println("Insert sql In [payarrToProcUpdation][sqlIns][1]........:: " + sqlIns);
								pstmt = conn.prepareStatement(sqlIns);
								pstmt.setString(1,tranID);
								pstmt.setString(2,currEmpCode);
								pstmt.setString(3,currPeriod);
								pstmt.setString(4,status);
								pstmt.setString(5,procType);
								pstmt.setTimestamp(6,new java.sql.Timestamp(System.currentTimeMillis()));
								pstmt.setString(7,GenericUtility.getInstance().getValueFromXTRA_PARAMS(xtraParams,"loginCode"));
								pstmt.setString(8,GenericUtility.getInstance().getValueFromXTRA_PARAMS(xtraParams,"termId"));
								int insCnt = pstmt.executeUpdate();
								if (insCnt == 1)
								{
									System.out.println("Inserted Into PAYARR_TO_PROC_TRACE Successfully.........");
								}
								else
								{
									errCode = "DS000";
									break;
								}
								pstmt.close();
								pstmt = null;
							}
							sqlIns = "INSERT INTO PAYARR_TO_PROC_TRACE (EMP_CODE, PRD_CODE, PROC_TYPE, TRAN_WINDOW, KEY_VALUES, CHG_DATE, CHG_USER, CHG_TERM) " + 
									" VALUES(?,?,?,?,?,?,?,?)" ;
							System.out.println("Insert sql In [payarrToProcUpdation][sqlIns][2]........:: " + sqlIns);
							pstmt = conn.prepareStatement(sqlIns);
							pstmt.setString(1,currEmpCode);
							pstmt.setString(2,currPeriod);
							pstmt.setString(3,procType);
							pstmt.setString(4,winName);
							pstmt.setString(5,keyStr);
							pstmt.setTimestamp(6,new java.sql.Timestamp(System.currentTimeMillis()));
							pstmt.setString(7,genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginCode"));
							pstmt.setString(8,genericUtility.getValueFromXTRA_PARAMS(xtraParams,"termId"));
							int insCnt = pstmt.executeUpdate();
							if (insCnt == 1)
							{
								System.out.println("Inserted Into PAYARR_TO_PROC_TRACE Successfully:: [insCnt].........::" + insCnt);
							}
							else
							{
								errCode = "DS000";
								break;
							}
							pstmt.close();
							pstmt = null;
						}
					}//End Of If Block
					rs.close();
					rs = null;
					stmt.close();
					stmt = null;
				}//End Inner While loop
				rsPrd.close();
				rsPrd = null;
				stmtPrd.close();
				stmt = null;
				if (errCode.trim().length() > 0)
				{
					//conn.rollback();
					break;
				}
				if (adCode != null && adBasic.trim().equals(adCode.trim()))
				{
					errCode = empBasicUpdate(currEmpCode, adCode, amount, effDate, expDate, conn);
					System.out.println("errCode Returned From empBasicUpdate()[errCode]......:: "+ errCode);
					if (errCode.trim().length() > 0)
					{
						break;
					}
				}
			}//End Outer While loop
		}//End Of Try Block
		catch (SQLException se)
		{
			System.out.println("Exception :AdmCommon :payarrToProcUpdation:" + se.getMessage() + ":");
			se.printStackTrace();
			try
			{
				conn.rollback();
			}
			catch(Exception se1){}
			throw new ITMException(se);
		}
		catch(Exception e)
		{
			System.out.println("Exception :[AdmCommon][function::payarrToProcUpdation()] :==>\n"+e.getMessage());
			e.printStackTrace();
			try
			{
				conn.rollback();
			}
			catch(Exception e1){}
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				System.out.println("Closing ResultSet, Statement etc... In [payarrToProcUpdation()]...............");
				if (rs != null)
				{
					rs.close();
					rs = null;
				}
				if (stmt != null)
				{
					stmt.close();
					stmt = null;
				}
				if (rs1 != null)
				{
					rs1.close();
					rs1 = null;
				}
				if (stmt1!= null)
				{
					stmt1.close();
					stmt1 = null;
				}
				if (rsEmp != null)
				{
					rsEmp.close();
					rsEmp = null;
				}
				if (stmtEmp != null)
				{
					stmtEmp.close();
					stmtEmp = null;
				}
				if (rsPrd != null)
				{
					rsPrd.close();
					rsPrd = null;
				}
				if (stmtPrd != null)
				{
					stmtPrd.close();
					stmtPrd = null;
				}
				if (pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch(Exception ex){}
		}
		return errCode;
	}
	//Function empBasicUpdate() Added by Gulzar 16/010/07
	public String empBasicUpdate(String currEmpCode, String adCode, double amount, String effDate, String expDate, Connection conn) throws ITMException
	{
		PreparedStatement pstmt = null;
		String updSql = "", errCode = "";
		long effTime = 0, expTime = 0, todayTime = 0;
		java.sql.Timestamp effectiveDate = null, expiryDate = null;
		java.sql.Timestamp toDate = new java.sql.Timestamp(System.currentTimeMillis());
		try
		{
			GenericUtility genericUtility = GenericUtility.getInstance();
			effectiveDate	= java.sql.Timestamp.valueOf(genericUtility.getValidDateTimeString(effDate,genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat()));
			expiryDate		= java.sql.Timestamp.valueOf(genericUtility.getValidDateTimeString(expDate,genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat()));

			effTime		= effectiveDate.getTime();
			expTime		= expiryDate.getTime();
			todayTime	= toDate.getTime();

			//if (toDate.compareTo(effectiveDate) >= 0 && toDate.compareTo(expiryDate) <= 0)
			if (todayTime >= effTime && todayTime <= expTime)
			{
				updSql = "UPDATE EMPLOYEE SET BASIC = BASIC + ? WHERE EMP_CODE = '"+currEmpCode+"' ";
				System.out.println("Update sql In [empBasicUpdate][updSql][2]........:: " + updSql);
				pstmt = conn.prepareStatement(updSql);
				pstmt.setDouble(1,amount);
				int updCnt = pstmt.executeUpdate();
				if (updCnt == 1)
				{
					System.out.println("Updated Into EMPLOYEE Successgully......! [updCnt] :: "+ updCnt);
				}
				else if (updCnt == 0)
				{
					errCode = "VMEMP1";
					System.out.println("Error In Updating EMPLOYEE [errCode] :: " + errCode);
				}
			}//End Of if Block
		}//End Of try Block
		catch (SQLException se)
		{
			System.out.println("Exception :AdmCommon :empBasicUpdate:" + se.getMessage() + ":");
			se.printStackTrace();
			try
			{
				conn.rollback();
			}
			catch(Exception se1){}
			throw new ITMException(se);
		}
		catch(Exception e)
		{
			System.out.println("Exception :[AdmCommon][function::empBasicUpdate()] :==>\n"+e.getMessage());
			e.printStackTrace();
			try
			{
				conn.rollback();
			}
			catch(Exception e1){}
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				System.out.println("Closing pstmt In [empBasicUpdate()]...............");
				if (pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch(Exception ex){}
		}
		return errCode;
	}
	//Function  getRelativeDate(String effDate, int no) added by Gulzar 15/01/07
	public String getRelativeDate(String effDate, int no) 
	{
		String relativeDate ="";
		java.util.Date date1 = null;

		try
		{
			GenericUtility genericUtility = GenericUtility.getInstance();
			SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getApplDateFormat());
			date1 = sdf.parse(effDate);
			Calendar calObject = Calendar.getInstance();
			calObject.setTime(date1);
			calObject.add(calObject.DATE,no);
			date1 = calObject.getTime();
			relativeDate = sdf.format(date1);
			System.out.println(" relativeDate : " +relativeDate);
		}
		catch(Exception e)
		{
			System.out.println("Exception :[AdmCommon][function::getRelativeDate()] :==>\n"+e.getMessage());
			e.printStackTrace();
		}
		return relativeDate;
	}
}