/*
Window Name : w_weekoff_creation
Button name : Weekly off
Auther		: Gulzar
*/

package ibase.webitm.ejb.adm.adv;

import java.rmi.RemoteException;
import java.sql.*;
import org.w3c.dom.*;
import javax.ejb.*;

import ibase.webitm.utility.ITMException;
import ibase.webitm.ejb.*;
import ibase.webitm.utility.GenericUtility;
import ibase.system.config.*;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import javax.ejb.Stateless; // added for ejb3

@Stateless // added for ejb3

public class WeekOffCreationPrc extends ProcessEJB implements WeekOffCreationPrcLocal,WeekOffCreationPrcRemote // SessionBean
{
	/*public void ejbCreate() throws RemoteException, CreateException 
	{
	}
	public void ejbRemove()
	{
	}
	public void ejbActivate() 
	{
	}
	public void ejbPassivate() 
	{
	}
	public String process() throws RemoteException,ITMException
	{
		return "";
	}*/

	public String process(String xmlString, String xmlString2, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		System.out.println("WeekOffCreationPrcEJB called.............!");
		Document dom = null,dom1 = null;
		String  resString = null;
		try
		{	
			if(xmlString != null && xmlString.trim().length() > 0)
			{
				System.out.println("XML String :"+xmlString);
				GenericUtility genericUtility = GenericUtility.getInstance();
				dom = genericUtility.parseString(xmlString);				
			}		
			resString = process(dom,dom1,windowName,xtraParams);
		}
		catch(Exception e)
		{
			System.out.println("Exception :WeekOffCreationPrcEJB : process(String xmlString):" + e.getMessage() + ":");
			throw new ITMException(e);
		}
		System.out.println("returning from Process "+resString);
	    return resString;
	}

	public String process(Document dom,Document dom1,String windowName,String xtraParams) throws RemoteException,ITMException
	{
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		PreparedStatement pstmt = null;
		String fromDt= "",toDt = "",rotate = "",offDay = "", offFor = "", retString = "", holTblNo = "";
		String chgTerm = "", chgUser = "", insSql = "", errCode = "", userId = "";
		int dayNo = 0, noOfDays = 0, minDays = 0, maxDays = 0, weeklyOffDay = 0, insCnt = 0, count = 0;
		java.util.Date fromDate = null, weeklyOffDate = null, toDate = null;
		
		GenericUtility genericUtility = GenericUtility.getInstance();
		try
		{	
			ConnDriver connDriver = new ConnDriver(); 
			conn = connDriver.getConnectDB("DriverITM");
			conn.setAutoCommit(false);
			fromDt		= genericUtility.getColumnValue("from_date",dom);
			toDt		= genericUtility.getColumnValue("to_date",dom);
			rotate		= genericUtility.getColumnValue("rotate",dom);
			offDay		= genericUtility.getColumnValue("off_day",dom);
			offFor		= genericUtility.getColumnValue("off_for",dom);
			holTblNo	= genericUtility.getColumnValue("hol_tblno",dom);
			
			System.out.println("fromDt From Dom........:: " + fromDt);
			System.out.println("toDt From Dom..........:: " + toDt);
			System.out.println("rotate From Dom........:: " + rotate);
			System.out.println("offDay From Dom........:: " + offDay);
			System.out.println("offFor From Dom........:: " + offFor);
			System.out.println("holTblNo From Dom......:: " + holTblNo);

			SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getApplDateFormat());
			fromDate	= sdf.parse(fromDt);
			toDate		= sdf.parse(toDt);
			weeklyOffDate = fromDate;
			weeklyOffDay = Integer.parseInt(offDay);

			if (rotate.equals("N"))
			{
				noOfDays = 7;
				if (offFor.equals("A"))
				{
					minDays = 1;
					maxDays = 31;
				}
				else if (offFor.equals("F"))
				{
					minDays = 1;
					maxDays = 7;
				}
				else if (offFor.equals("S"))
				{
					minDays = 8;
					maxDays = 14;
				}
				else if (offFor.equals("T"))
				{
					minDays = 15;
					maxDays = 21;
				}
				else if (offFor.equals("O"))
				{
					minDays = 22;
					maxDays = 28;
				}
				else if (offFor.equals("I"))
				{
					minDays = 29;
					maxDays = 31;
				}
			}
			else if (rotate.equals("Y"))
			{
				minDays = 1;
				maxDays = 31;
				noOfDays = 8;
			}
			dayNo = getDayNumber(fromDate);
			System.out.println("dayNo Returned From [getDayNumber()] :: "+ dayNo);
			while (weeklyOffDay != dayNo)
			{
				weeklyOffDate = sdf.parse(getRelativeDate(weeklyOffDate, 1));
				dayNo = getDayNumber(weeklyOffDate);
			}
			insSql = "INSERT INTO HOLIDAY(HOL_TBLNO,HOL_DATE,DESCR,CHG_DATE,CHG_USER,CHG_TERM,NO_DAYS,HOL_TYPE ) " +
					" VALUES (?,?,'WEEKLY OFF',?,?,?,1,'W')";
			pstmt = conn.prepareStatement(insSql);
			while (weeklyOffDate.compareTo(toDate) <= 0)
			{
				if (getDay(weeklyOffDate) >= minDays && getDay(weeklyOffDate) <= maxDays)
				{
					pstmt.setString(1,holTblNo);
					pstmt.setTimestamp(2,java.sql.Timestamp.valueOf(genericUtility.getValidDateTimeString(sdf.format(weeklyOffDate),genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat())));
					pstmt.setTimestamp(3,new java.sql.Timestamp(System.currentTimeMillis()));
					pstmt.setString(4,genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginCode"));
					pstmt.setString(5,genericUtility.getValueFromXTRA_PARAMS(xtraParams,"termId"));
					insCnt = pstmt.executeUpdate();
					if (insCnt == 1)
					{
						System.out.println("Inserted Into HOLIDAY Successfully....[insCnt]:: " + insCnt);
						count++;
					}
					else
					{
						errCode = "DS000";
						System.out.println("Inserted Into HOLIDAY Failed.......! [errCode] :: " + errCode);
						break;
					}
					pstmt.clearParameters();
				}
				weeklyOffDate = sdf.parse(getRelativeDate(weeklyOffDate, noOfDays));
			}
			System.out.println("count....:: " + count);
			if (errCode.trim().length() > 0)
			{
				System.out.println("Rolling Back The Changes.......! " + errCode);
				conn.rollback();
			}
			else
			{
				errCode = "VPSUCC1";
				System.out.println("Commiting The Changes.......! " + errCode);
				conn.commit();
			}
			userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"userId");
			ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
			retString = itmDBAccessEJB.getErrorString("",errCode,userId);
		}
		catch(SQLException se)
		{
			System.out.println("Exception : WeekOffCreationPrcEJB : process()" +se.getMessage());
			try
			{
				conn.rollback();
			}
			catch(Exception se1){}
			throw new ITMException(se);
		}
		catch(Exception e)
		{
			System.out.println("Exception :WeekOffCreationPrcEJB :process():"+e.getMessage());
			try
			{
				conn.rollback();
			}
			catch(Exception e1){}
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				System.out.println("Closing Database Connection......");
				if (pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
				if (conn != null)
				{
					conn.close();
					conn = null;
				}
			}catch(Exception se){}
		}
		return retString;  	
	}	
	private int getDayNumber(java.util.Date fromDate)
	{
		int noOfDays = 0;
		try
		{
			Calendar calObj = Calendar.getInstance();
			calObj.setTime(fromDate);
			noOfDays = calObj.get(calObj.DAY_OF_WEEK);
		}
		catch(Exception e)
		{
			System.out.println("Exception : " + e);
		}
		System.out.println("noOfDays In [getDayNumber()] :: " + noOfDays);
		return noOfDays;
	}
	private int getDay(java.util.Date fromDate)
	{
		int noOfDays = 0;
		try
		{
			Calendar calObj = Calendar.getInstance();
			calObj.setTime(fromDate);
			noOfDays = calObj.get(calObj.DAY_OF_MONTH);
		}
		catch(Exception e)
		{
			System.out.println("Exception : " + e);
		}
		System.out.println("noOfDays In [getDay()] :: " + noOfDays);
		return noOfDays;
	}
	private String getRelativeDate(java.util.Date effDate, int no) 
	{
		String relativeDate ="";
		try
		{
			SimpleDateFormat sdf = new SimpleDateFormat(GenericUtility.getInstance().getApplDateFormat());
			Calendar calObject = Calendar.getInstance();
			calObject.setTime(effDate);
			calObject.add(calObject.DATE,no);
			effDate = calObject.getTime();
			relativeDate = sdf.format(effDate);
		}
		catch(Exception e)
		{
			System.out.println("Exception :[AdmCommon][function::getRelativeDate()] :==>\n"+e.getMessage());
			e.printStackTrace();
		}
		System.out.println(" relativeDate In [getRelativeDate()]:: " +relativeDate);
		return relativeDate;
	}
}