package ibase.webitm.ejb.adm;

import ibase.webitm.utility.*;
//import ibase.utility.CommonConstants;
import ibase.system.config.*;
//import java.text.*;
import java.util.*;
//import javax.xml.parsers.*;
import javax.ejb.*;
//import javax.naming.InitialContext;
import java.io.*;

import java.util.Calendar;
import java.util.Date;
import java.sql.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.rmi.RemoteException;
import org.w3c.dom.*;
import ibase.webitm.utility.ITMException;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.ejb.*;

import javax.ejb.Stateless; // added for ejb3


//public class SReturnPrsEJB extends ValidatorEJB implements SessionBean
@Stateless // added for ejb3
public class CopyCadrePerkParamPrs extends ValidatorEJB implements CopyCadrePerkParamPrsLocal, CopyCadrePerkParamPrsRemote
{
	
	public String preSaveRec() throws RemoteException, ITMException
	{
		return "";
	}
	
	public String preSaveRec(String xmlString1, String domId, String objContext, String editFlag, String xtraParams, Connection conn) throws RemoteException, ITMException
	{
		System.out.println("@@@@@@@@********* CopyCadrePERKParamPrs Called *******@@@@@@@@");
		Document dom = null;
		String errString = "";
		//ITMDBAccessEJB itmDBAccessLocal = new ITMDBAccessEJB();
		try
		{
			if (xmlString1 != null && xmlString1.trim().length() > 0)
			{
				dom = GenericUtility.getInstance().parseString(xmlString1);
				errString = executepreSaveRec(dom,domId,objContext,editFlag,xtraParams,conn);
				if (errString == null || errString.trim().length() == 0)
				{
					
					//errString = itmDBAccessLocal.getErrorString("","VTMCONF2","");
				}
				else
				{
					conn.rollback();
					//errString = itmDBAccessLocal.getErrorString("","VMPROCUSG","");
				}
			}
		}
		catch(Exception e)
		{
			System.out.println("Exception :CopyPayParamPrs :preSaveRec(): " + e.getMessage()+ ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		return errString;
	}
	private String executepreSaveRec(Document dom, String domID, String ObjContext, String editFlag, String xtraParams, Connection conn) throws RemoteException, ITMException
	{
		//Connection conn = null;
		PreparedStatement pstmt = null,pstmt1 = null,pstmtInser = null;
		ResultSet rs = null ,rs1 = null;
		String pay_table = "",new_pay_table="";
		String sql = "",sql1 = "",sqlInser;
		String chgUser = "",chgTerm = "" ;
		String cadre_code="",new_cadre_code="";
		String ad_code="",type="";
		String prop_yn="";
		
		String exp_date=null,eff_date=null,month_code="";
		
		String  ad_code_main="" ;
		double cycle_time=0.0,cycle_start=0.0,cycle_end=0.0,validity_period=0.0;
		
		String last_proc_for="",next_proc_date="";
		
		System.out.println("@@@@@@@@@@@@@@@@@@@@2 TEST");
		
		double amount=0.0,min_basic=0.0,max_basic=0.0;
		double min_amt=0.0,max_amt=0.0;
	
		int cnt = 0,updCnt = 0;
	 
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
		GenericUtility genericUtility = GenericUtility.getInstance();		
		ITMDBAccessEJB itmDBAccessLocal = new ITMDBAccessEJB();
		String errString = "";
		String cadreCode = "";
		boolean insertFlag=false;
		try
		{	
			ConnDriver connDriver = new ConnDriver();			
			conn = connDriver.getConnectDB("DriverITM");
			conn.setAutoCommit(false);
			pay_table = genericUtility.getColumnValue("pay_table",dom);
			//varName = genericUtility.getColumnValue("var_name",dom);
			new_pay_table = genericUtility.getColumnValue("new_pay_table",dom);
			new_cadre_code = genericUtility.getColumnValue("new_cadre_code",dom);
			cadreCode = genericUtility.getColumnValue("cadre_code",dom);

			String currAppdate ="";
			java.sql.Timestamp currDate = null;
			Object date = null;
			currDate =new java.sql.Timestamp(System.currentTimeMillis()) ;
			System.out.println(genericUtility.getDBDateFormat());
			SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getDBDateFormat());
			date = sdf.parse(currDate.toString());
			currDate =	java.sql.Timestamp.valueOf(sdf.format(date).toString() + " 00:00:00.0");
			currAppdate = new SimpleDateFormat(genericUtility.getApplDateFormat()).format(currDate).toString();
			
			chgUser = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"chg_user");
			
			chgTerm = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"chg_term");
		
			
			if( pay_table == null || pay_table.trim().length() ==0 )
			{
				//errString = itmDBAccessEJB.getErrorString("","PRDCODNULL","");
				//return errString;
			}
			else if( new_pay_table == null || new_pay_table.trim().length() == 0 )
			{
				//------PAY TABLE NOT LEAVE EMPTY
				errString = itmDBAccessEJB.getErrorString("","NEWPAYTBL","");
				return errString;
			}
			else if( new_pay_table != null && new_pay_table.trim().length() > 0 )
			{
				/*if( new_pay_table.trim().length() > 5 )
				{
					
					errString = itmDBAccessEJB.getErrorString("","NEWSITEINV","");
            		return errString;
					
				}*/
				/*else if(checkValidity(new_pay_table, "pay_table", "site", conn)<=0){
					insertFlag=true;
					errString = itmDBAccessEJB.getErrorString("","NEWSITNEXI","");
	        		return errString;
				}*/
				
			}
			
			/*ME if( pay_table != null && pay_table != null && new_pay_table.trim().length() > 0 && pay_table.trim().length() > 0 )
			{	
			//sql = " SELECT var_name,var_type,var_value,descr,var_subs FROM payrparm WHERE prd_code = ? ";   // and var_name = ?";
				
			sql="SELECT * FROM PAYTABLE WHERE PAY_TABLE=?";
			pstmt =  conn.prepareStatement(sql);
			pstmt.setString(1,new_pay_table);
			rs = pstmt.executeQuery();
			if(rs.next()){
			}else{
				errString = itmDBAccessEJB.getErrorString("","NEWPAYNO","");//New Pay table not available
				return errString;
			}	*/
			
			
			
			if(new_pay_table!=null && checkValidity(new_pay_table, "pay_table", "PAYTABLE", conn)<=0){
				//insertFlag=true;
				errString = itmDBAccessEJB.getErrorString("","NEWPAYNO","");
        		return errString;
			}
			
			if (new_cadre_code == null || new_cadre_code.trim().length() == 0)
			{
				errString = itmDBAccessEJB.getErrorString("","VTCPCPRK01","");
        		return errString;
			}
			if( new_cadre_code!=null && checkValidity(new_cadre_code, "CADRE_CODE", "CADRE", conn)<=0){
				//insertFlag=true;
				errString = itmDBAccessEJB.getErrorString("","CCNOEXIST","");
        		return errString;
			}
			
			
			System.out.println("BEFORE PAYTABLE CADRE CHECK ............");
			System.out.println("----------- pay_table : "+pay_table+" grade_code : "+cadre_code);	
			
				
			// sql =	"SELECT * FROM CADRE_PERK WHERE PAY_TABLE=?"; 
			sql =	"SELECT * FROM CADRE_PERK WHERE PAY_TABLE=? AND CADRE_CODE = ?"; 
			pstmt =  conn.prepareStatement(sql);
			pstmt.setString(1,pay_table);
			pstmt.setString(2,cadreCode);
			//pstmt.setString(2,varName);
			rs = pstmt.executeQuery();
			while(rs.next())
			{
				
				cadre_code = rs.getString("cadre_code");
				ad_code_main =rs.getString("ad_code__main");
				ad_code =rs.getString("ad_code");
				eff_date= rs.getString("eff_date");
				exp_date=rs.getString("exp_date");
				java.sql.Timestamp expDateChg = null;
				expDateChg=getTimestamp(exp_date);
				type=rs.getString("type");
				amount=rs.getDouble("amount");
				cycle_time=rs.getDouble("cycle_time");
				cycle_start=rs.getDouble("cycle_start");
				cycle_end=rs.getDouble("cycle_end");
				last_proc_for=rs.getString("last_proc_for");
				
				java.sql.Timestamp last_proc_forChg = null;
				if (last_proc_for != null && last_proc_for.trim().length() > 0)
				{
					last_proc_forChg=getTimestamp(last_proc_for);
				}

				next_proc_date=rs.getString("next_proc_date");
				
				java.sql.Timestamp next_proc_dateChg = null;
				if (next_proc_date != null && next_proc_date.trim().length() > 0)
				{
					next_proc_dateChg=getTimestamp(next_proc_date);
				}
				validity_period=rs.getDouble("validity_period");
				
				//sql1 = "SELECT count(*) FROM CADRE_PERK WHERE prd_code = ? and var_name = ? ";
				sql1 ="SELECT count(*) FROM CADRE_PERK WHERE PAY_TABLE = ? and CADRE_CODE=? and AD_CODE=? and AD_CODE__MAIN=? and EFF_DATE=?";
				pstmt1 =  conn.prepareStatement(sql1);
				
				if(new_pay_table != null && new_pay_table.trim().length() > 0 && new_cadre_code==null){
					//if only new pay table enters then  copy data from paytable and against CADRE code into new paytable
					System.out.println("COUNT CONDTION 1");
					pstmt1.setString(1, new_pay_table);
					pstmt1.setString(2, cadre_code);
					
					
				}else if(new_pay_table == null   && new_cadre_code!=null && new_cadre_code.trim().length() > 0){
					//if only new gradecode enters then  copy data from paytable and against CADRE code into exiting paytable with new gradecode
					System.out.println("COUNT CONDTION 2");
					pstmt1.setString(1, pay_table);
					pstmt1.setString(2, new_cadre_code);
					 
					
				} else if(new_pay_table != null && new_pay_table.trim().length() > 0 && new_cadre_code!=null && new_cadre_code.trim().length() > 0){
					//if both new gradecode and gradecode enters then  copy data from paytable and against CADRE code into new paytable and new gradecode
					System.out.println("COUNT CONDTION 3");
					pstmt1.setString(1, new_pay_table);
					pstmt1.setString(2, new_cadre_code);
					 
				} else if(new_pay_table == null   && new_cadre_code==null ){
					// validation
					System.out.println("NEW CADRE CODE AND PAYTABLE BOTH ARE EMPTY.........");
					errString = itmDBAccessEJB.getErrorString("","PAYCCTBL","");
	        		return errString;
					
				}
				
				
				//pstmt1.setString(1, new_pay_table);ME
				//pstmt1.setString(2, cadre_code);ME
				pstmt1.setString(3, ad_code);
				pstmt1.setString(4, ad_code_main);
				java.sql.Timestamp effDateChg = null;
				effDateChg=getTimestamp(eff_date);
				pstmt1.setTimestamp(5, effDateChg);
				rs1 = pstmt1.executeQuery();
				if(rs1.next())
				{
					cnt =  rs1.getInt(1);
				}
				rs1.close();
				rs1 = null;
				pstmt1.close();
				pstmt1 = null;
				System.out.println("@@@@@:::cnt:["+cnt+"]");
				if(cnt == 0)
				{
					sqlInser = "INSERT INTO CADRE_PERK (pay_table, cadre_code, ad_code,ad_code__main, eff_date, exp_date, type, amount, cycle_time, cycle_start, cycle_end, last_proc_for,next_proc_date,chg_date,chg_user,chg_term,validity_period) "
						       +" VALUES (?,?,?, ?,?,?, ?,?,?, ?,?,?,?,?,?,?,?)  ";
					pstmtInser	= conn.prepareStatement(sqlInser);
					
					
					if(new_pay_table != null && new_pay_table.trim().length() > 0 && new_cadre_code==null  ){
						//if only new pay table enters then  copy data from paytable and against CADRE code into new paytable
						System.out.println("INSERT CONDTION 1");
						pstmtInser.setString(1, new_pay_table);
						pstmtInser.setString(2, cadre_code);
						
					}else if(new_pay_table == null   && new_cadre_code!=null && new_cadre_code.trim().length() > 0){
						//if only new gradecode enters then  copy data from paytable and against CADRE code into exiting paytable with new gradecode
						System.out.println("INSERT CONDTION 2");
						pstmtInser.setString(1, pay_table);
						pstmtInser.setString(2, new_cadre_code);
						
					} else if(new_pay_table != null && new_pay_table.trim().length() > 0 && new_cadre_code!=null && new_cadre_code.trim().length() > 0){
						//if both new gradecode and gradecode enters then  copy data from paytable and against CADRE code into new paytable and new gradecode
						System.out.println("INSERT CONDTION 3");
						pstmtInser.setString(1, new_pay_table);
						pstmtInser.setString(2, new_cadre_code);
						
					}
					
					
					
					//pstmtInser.setString(1,new_pay_table);me
					//pstmtInser.setString(2, cadre_code);me
					pstmtInser.setString(3, ad_code);
					pstmtInser.setString(4, ad_code_main);
					pstmtInser.setTimestamp(5,effDateChg);
					pstmtInser.setTimestamp(6,expDateChg);
					pstmtInser.setString(7, type);   
					pstmtInser.setDouble(8,amount);
					pstmtInser.setDouble(9,cycle_time);
					pstmtInser.setDouble(10,cycle_start);
					pstmtInser.setDouble(11,cycle_end);
					pstmtInser.setTimestamp(12,last_proc_forChg);
					pstmtInser.setTimestamp(13, next_proc_dateChg);
					pstmtInser.setTimestamp( 14, currDate);
					pstmtInser.setString(15, chgUser);
					pstmtInser.setString(16, chgTerm);
					pstmtInser.setDouble(17,validity_period);
					
					System.out.println("@@@@@@@@@@@@@@ BEFORE INSERT "+new_pay_table);
					
					updCnt = pstmtInser.executeUpdate();
					pstmtInser.close();
					pstmtInser=null;
					if(updCnt > 0 )
					{
						conn.commit();
						System.out.println("@@@@@ Record inserted for table no["+new_pay_table +"]:::::::: @@@@@");
					}
					 
				}
				else
				{
					
					 System.out.println("@@@@@ :::::Record already exist for PeriodCode["+new_pay_table +"]::varName["+ cadre_code +"]  :::::: @@@@@");
					//errString = itmDBAccessLocal.getErrorString("","VMDUPREC1","");
					// errString = itmDBAccessEJB.getErrorString("","NEWPAYAA","");
				}
				
			}
			if(rs != null)
			{
				rs.close();
				rs = null;
			}
			if(pstmt != null)
			{
				pstmt.close();
				pstmt = null;
			}
			 		
			//valueXmlString.append("</Root>\r\n");
		} // end of try 
		catch(Exception e)
		{
			try
			{
				conn.rollback();
			}
			catch(Exception ex)
			{
				throw new ITMException(ex);

			}
			throw new ITMException(e);

		}
		finally
		{
			try
			{
				conn.close();
				conn = null;
			}
			catch(Exception e)
			{
				throw new ITMException(e);
			}
		}
		return errString ;
	}
	
public String getDD_MM_YYYY_format(String str) throws Exception{
		
		  DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		  Date date;
		  String dd_mm_yyyy="";
	
			date = (Date)formatter.parse(str);
			System.out.println("DDMMYYYY="+date);
			SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy");   
			dd_mm_yyyy=format.format(date);
			
	       //String orcleFormat= oracleFormatDate(dd_mm_yyyy); 
	       System.out.println("orcleFormat dd-mm-yyyy=="+dd_mm_yyyy);
	     return dd_mm_yyyy;
	}
	 
public Timestamp getTimestamp(String str) throws Exception{
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.S");
		java.util.Date date = sdf.parse(str);
		java.sql.Timestamp timestamp = new java.sql.Timestamp(date.getTime());
		//System.out.println("====="+timestamp);
		return timestamp;
		
	}
 
	
	
	public int checkValidity(String retrival, String column_name, String table_name,  Connection from_site_conn) throws SQLException{
		boolean flag=false;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		String Query="";
		Connection conn=null;
		int count=0;
		Connection localConnection =null;
			
		try{
			       conn = from_site_conn;
			       Query="select count("+column_name+")  from "+table_name+" where "+column_name+"='"+retrival+"'";
			       System.out.println("====QUERY=="+Query);
			       pstmt=conn.prepareStatement(Query);
			       rs=pstmt.executeQuery(Query);
			       if(rs.next()){
			    	   count=rs.getInt(1);
			       	}
			      
		 }catch(Exception e){
			 e.printStackTrace();
		 }finally{
			 if(pstmt!=null){
				 pstmt.close();
				 pstmt=null;
			 }
			 if(rs!=null){
				 rs.close();
				 rs=null;
			 }
			 		}
		 System.out.println("count="+count);
		return count;
		}

}



