package ibase.webitm.ejb.sys;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import com.mysql.jdbc.PreparedStatement;

import ibase.system.config.ConnDriver;
import ibase.utility.BaseLogger;
import ibase.utility.CommonConstants;
import ibase.utility.E12GenericUtility;
import ibase.utility.UserInfoBean;
import ibase.webitm.ejb.ActionHandlerEJB;
import ibase.webitm.ejb.DBAccessEJB;
import ibase.webitm.ejb.ITMDBAccessEJB;
import ibase.webitm.ejb.ITMUploadFileEJB;
import ibase.webitm.ejb.MasterApplyEJB;
import ibase.webitm.utility.ITMException;
import ibase.webitm.utility.RestAPIServiceUtility;
import ibase.webitm.utility.VisionEDIUtility;
import net.sf.saxon.functions.Evaluate.PreparedExpression;
/*
 * Author: Gagan B.
 * Purpose of the class: On click of Reload button in batch data upload screen LOAD_STAT should be changed from "E" to "N". 
 * After that the data should be saved in transaction (call transLoad method.)
 * Reload button should be used only in cases like below.
 * E.g. 

1. Period not defined. 
2. Master not available. 
3. Some database access was not provided. 
 * */
public class BatchloadReload extends ActionHandlerEJB
{
	

	
	protected ibase.utility.UserInfoBean userInfo = null;

	
	
	
	@Override
	public String actionHandler(String tranId, String xtraParams, String forcedFlag) throws RemoteException, ITMException 
	{
		//Connection  connectionObject = null;
		String errString = "";
		try
		{
			Connection conn = getConnection();
			UpdateLoadStatus updateLoadStatus = new UpdateLoadStatus();
			updateLoadStatus.setUserInfo(getUserInfo() );
			//updateLoadStatus.UpdateLoadStat(tranId, xtraParams, forcedFlag);
			
			
			BaseLogger.log("3",null,null,"tranId from BatchloadReload:: ["+tranId+"]");
			String batchid = "";
	        int tranIdend = tranId.indexOf(":");
	        if (tranIdend != -1) 
			{
	        	batchid = tranId.substring(0 , tranIdend); 
			}
	        
	        System.out.println("batchid:" + batchid);
	        String appId = "";
			
			
	        
	        
			String ediAddr = "";
			if (getUserInfo() != null) 
			{
				DBAccessEJB dbAccessEJB = new DBAccessEJB();
				try 
				{
					ediAddr = dbAccessEJB.getDBColumnValue("BATCHLOAD", "EDI_ADDR", "BATCH_ID  = '"+batchid+"'", getUserInfo().getTransDB());
				} 
				catch (RemoteException | ITMException e) 
				{
					e.printStackTrace();
				}
			}
			
			if(!ediAddr.equalsIgnoreCase(""))
			{
				int ediAddriend = ediAddr.indexOf("_");
				if (ediAddriend != -1)
				{
					ediAddr= ediAddr.substring(0 , ediAddriend);
					appId = ediAddr;
				}
			}
			BaseLogger.log("3",null,null,"tranId from BatchloadReload:: ["+tranId+"]");
			BaseLogger.log("3",null,null,"appId from BatchloadReload:: ["+appId+"]");
			BaseLogger.log("3",null,null,"errString from BatchloadReload["+errString+"]");
			

			
			String winName = "";
			if (getUserInfo() != null) 
			{
				DBAccessEJB dbAccessEJB = new DBAccessEJB();
				try 
				{
					winName  = dbAccessEJB.getDBColumnValue("BATCHLOAD", "WIN_NAME", "BATCH_ID  = '"+batchid+"'", getUserInfo().getTransDB());
				} 
				catch (RemoteException | ITMException e) 
				{
					e.printStackTrace();
				}
			}
			
			String dataFileName = "";
			String serviceName = winName.substring(2);
			String enterprise = getUserInfo().getEnterprise();
			String addUser = getUserInfo().getLoginCode();
			
			BaseLogger.log("3",null,null,"serviceName from BatchloadReload:: ["+serviceName+"]");
			BaseLogger.log("3",null,null,"enterprise from BatchloadReload:: ["+enterprise+"]");
			
			if (getUserInfo() != null) 
			{
				DBAccessEJB dbAccessEJB = new DBAccessEJB();
				try 
				{
					dataFileName  = dbAccessEJB.getDBColumnValue("BATCHLOAD", "DATA_FILE_NAME", "BATCH_ID  = '"+batchid+"'", getUserInfo().getTransDB());
				} 
				catch (RemoteException | ITMException e) 
				{
					e.printStackTrace();
				}
			}
			
			String fromPath = CommonConstants.EDI_DATA_PATH + File.separator + serviceName + File.separator + enterprise + File.separator + appId + File.separator + dataFileName;
			BaseLogger.log("3",null,null,"From Path: " + fromPath);
			
			String fileType = dataFileName.substring( dataFileName.lastIndexOf(".") + 1 );
			BaseLogger.log( "3", null, null, "fileType : ["+ fileType +"]" );
			String dataDumpFolderName = "";
			if( "json".equalsIgnoreCase( fileType ) )
			{
				dataDumpFolderName = "JSON_UPLOAD";
			}
			else
			{
				dataDumpFolderName = "XLS_UPLOAD";
				fileType = "xml";
			}
			
			String toPath = CommonConstants.JBOSSHOME + File.separator + dataDumpFolderName + File.separator + addUser + File.separator + batchid + File.separator + dataFileName;
			BaseLogger.log("3",null,null,"To Path: " + toPath);
			
			moveFile(fromPath, toPath);
			

			
//			
			
			
//			******************DANIEL changes
			//reloadLoadStatE

	        errString = reloadLoadStatE(batchid,appId);
	        // errString = readFileContents(batchid,appId);


//***************
			
			
			//ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
			//errString = itmDBAccessEJB.getErrorString("","RLOADSUC",addUser,"",conn);
		}
		catch(Exception e)
		{
			BaseLogger.log("3",null,null,"BATCHLOAD Exception ::"+e.getMessage());
			throw new ITMException(e);
		}
		BaseLogger.log("3",null,null,"Returning Result ::"+errString);
		return errString;
	}
	
	public String moveFile(String fromPath, String toPath)
	{
		String result = "";
		try 
		{
			Path temp = Files.move(Paths.get(fromPath), Paths.get(toPath));
			if (temp != null)
			{
				BaseLogger.log("3",null,null,"File moved sucessfully!");
				result = "Y";
			}
			else
			{
				BaseLogger.log("3",null,null,"Failed to move file.");
				result = "N";
			}
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		}
		return result;
	}
	
	
	
	//reloadLoadStatE
	//reload
	
	public String reloadLoadStatE(String batchID,String appId) throws RemoteException, ITMException, SQLException
	{
		
		
		String input = "",fileName="",filepath ="",errorString="";
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
		Connection conn = getConnection();
		java.sql.PreparedStatement pstmt = null, pstmt2=null;

		try {
			
			String addUser = getUserInfo().getLoginCode();

			
			DBAccessEJB dbacessEJb = new DBAccessEJB();
			
			String loadstat = dbacessEJb.getDBColumnValue("BATCHLOAD", "LOAD_STAT", "BATCH_ID  = '"+batchID+"' ", getUserInfo().getTransDB());
			BaseLogger.log("3",null,null,"DANiel appId22: " + appId);
			BaseLogger.log("3",null,null,"DANiel appId: " + appId);
			BaseLogger.log("3",null,null,"DANiel loadstat: " + loadstat);
			BaseLogger.log("3",null,null,"DANiel batchID: " + batchID);

			if("E".equalsIgnoreCase(loadstat))

			{
				
//				 fileName = dbacessEJb.getDBColumnValue("BATCHLOAD", "DATA_FILE_NAME", "BATCH_ID  = '"+batchID+"' ", getUserInfo().getTransDB());
//				BaseLogger.log("3",null,null,"DANiel data_File_Name: " + fileName);
//				
//				if(fileName.isEmpty() || fileName.trim().length() == 0 || fileName == null )
//					
//				{
//					errorString = itmDBAccessEJB.getErrorString("","FLNTFND",addUser,"",conn);
//				}
//				
//				filepath = "/wildfly/upload_failed/"+fileName;
//				BaseLogger.log("3",null,null,"DANiel filepath: " + filepath);
//
//				BufferedReader bufferreader = new BufferedReader(new FileReader(filepath));
//				StringBuilder sb = new StringBuilder();
//				String line = bufferreader.readLine();
//				
//				while(line != null)
//				{
//					sb.append(line);
//					line = bufferreader.readLine();
//				}
//				
//				 	input = sb.toString();
//					BaseLogger.log("3",null,null,"DANiel input: " + input);
//					BaseLogger.log("3",null,null,"DANiel StringBuilder sb: " + sb);
				
					//errString = input;
					
				
					
//					String sql = "UPDATE BATCHLOAD SET LOAD_STAT = 'R' WHERE BATCH_ID = '"+batchID+ "' ";
//					 pstmt = conn.prepareStatement(sql);
//					int sqlresult =  pstmt.executeUpdate();
//					BaseLogger.log("3",null,null,"DANiel new sqlresult: " + sqlresult);

					
					//BaseLogger.log("3",null,null,"DANiel new loadstat: " + loadstat);

//					VisionEDIUtility visionediutility = new VisionEDIUtility();
//					String transload  = visionediutility.transLoad(appId, getUserInfo(), input, "writeFilesavetrans");
//					BaseLogger.log("3",null,null,"DANiel transload method value: " + transload);

					

//					VisionEDIUtility visionediutility = new VisionEDIUtility();
//					String transreload =visionediutility.transReload(appId, getUserInfo(), batchID);
//					BaseLogger.log("3",null,null,"DANiel transreload method value: " + transreload);

//					String transreloadresult = reloadTransLoad(appId, getUserInfo(), batchID);
//					BaseLogger.log("3",null,null,"DANiel reloadtransload method value: " + transreloadresult);

					
					String transreloadresult = transReload(appId, getUserInfo(), batchID);
					BaseLogger.log("3",null,null,"DANiel transreloadresult method value: " + transreloadresult);

					
					String sql2 = "UPDATE BATCHLOAD SET LOAD_STAT = 'Y' WHERE BATCH_ID = '"+batchID+ "' ";
					 pstmt2 = conn.prepareStatement(sql2);
					 int sqlresult2 =  pstmt2.executeUpdate();
					
					BaseLogger.log("3",null,null,"DANiel second sqlresult: " + sqlresult2);
					
					
					//**********
//					String result = reloadTransLoad(appId, userInfo, batchID, input);
//					BaseLogger.log("3",null,null,"DANiel transload replicated method response " + result);
					//*********
					
					
					
					errorString = itmDBAccessEJB.getErrorString("","RLOADSUC",addUser,"",conn);
					
					
	
			}
			
			else
			{
				errorString = itmDBAccessEJB.getErrorString("","RLOADFAIL",addUser,"",conn);
				//errString = itmDBAccessEJB.getErrorString("","RLOADSUC",addUser,"",conn);

				//reload will only work for load stat E
			}
				
			
						
		}
		catch(Exception e )
		{
			e.printStackTrace();
			System.out.println("Exception is"+e);
		}

		
		finally
		{
		
			try {
				
				if(conn != null)
				{
					conn.close();
					conn = null;
				
				}
				
				if (pstmt != null) {
					
					pstmt.close();
					pstmt = null;
				}
				
				if(pstmt2 !=null )
				{
					pstmt2.close();
					pstmt2 = null;
				}
				
			}
			
			catch (Exception e) {
				
				e.printStackTrace();
				System.out.println("EXception is"+e);
			}
				
		}
		BaseLogger.log("3",null,null,"DANiel errorString: " + errorString);
		return errorString;
	}
	
	
	public String readUploadFailFileContents(String batchID) throws ITMException, IOException
	{
		
		String errorString = "";
		DBAccessEJB dbacessEJb = new DBAccessEJB();
		String addUser = getUserInfo().getLoginCode();
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
		String filepath = "",fileName="";
		Connection conn = getConnection();
		String input = "";
		
		 fileName = dbacessEJb.getDBColumnValue("BATCHLOAD", "DATA_FILE_NAME", "BATCH_ID  = '"+batchID+"' ", getUserInfo().getTransDB());
		BaseLogger.log("3",null,null,"DANiel data_File_Name: " + fileName);
		
		if(fileName.isEmpty() || fileName.trim().length() == 0 || fileName == null )
			
		{
			errorString = itmDBAccessEJB.getErrorString("","FLNTFND",addUser,"",conn);
		}
		
		filepath = "/wildfly/upload_failed/"+fileName;
		BaseLogger.log("3",null,null,"DANiel filepath: " + filepath);

		BufferedReader bufferreader = new BufferedReader(new FileReader(filepath));
		StringBuilder sb = new StringBuilder();
		String line = bufferreader.readLine();
		
		while(line != null)
		{
			sb.append(line);
			line = bufferreader.readLine();
		}
		
		 	input = sb.toString();
			BaseLogger.log("3",null,null,"DANiel input: " + input);
			BaseLogger.log("3",null,null,"DANiel StringBuilder sb: " + sb);
			bufferreader.close();
		
		return input;
	}
	
	
	
	
//	
//	public String reloadTransLoad(String appId, UserInfoBean userinfo,String batchId) throws Exception
//	{
//		
//		String result = "";
//		Connection conn = null;
//		java.sql.PreparedStatement pstmt = null;
//		ResultSet rs = null;
//		String inputData = "";
//		String PKValue = "";
//		
//		try {
//			
//			
//			ConnDriver connDriver = new ConnDriver();
//			conn = connDriver.getConnectDB( userinfo.getTransDB() );
//			connDriver = null;
//			
//			BaseLogger.log( "3", userinfo, null, "daniel appId : ["+ appId +"]" );
//			
//			String appIdAddr = "";
//			if ( appId.length() > 0 )
//			{
//				appIdAddr = (appId + "_");
//				BaseLogger.log( "3", userinfo, null, "daniel appIdAddr : ["+ appIdAddr +"]" );
//			}
//			
//			String sql = "select * from batchload where batch_id = '"+batchId+"' ";
//			pstmt = conn.prepareStatement( sql );
//			rs = pstmt.executeQuery();
//			BaseLogger.log( "3", userinfo, null, "daniel sql : ["+ sql +"]" );
//		
//			HashMap<Integer, HashMap<String, String>> dataMap = new LinkedHashMap<Integer, HashMap<String,String>>();
//
//			ResultSetMetaData rsmd = rs.getMetaData();
//			int noOfColumns = rsmd.getColumnCount();
//			
//			while( rs.next() )
//			{
//				HashMap<String, String> tempMap = new HashMap<String, String>();
//				for(int ctr = 1; ctr <= noOfColumns; ctr++)
//				{
//					if( "mysql".equalsIgnoreCase( CommonConstants.DB_NAME ) )
//					{
//						tempMap.put( rsmd.getColumnName(ctr).toUpperCase(), rs.getString(ctr) );
//					}
//					else
//					{
//						tempMap.put( rsmd.getColumnName(ctr), rs.getString(ctr) );
//					}
//				}
//				dataMap.put( 1, tempMap ); // Changed by Gagan B. for storing only latest transaction in map.
//			}
//			rs.close();
//			rs = null;
//			pstmt.close();
//			pstmt = null;
//		
//		
//			MasterApplyEJB masterApplyEJB = new MasterApplyEJB();
//			masterApplyEJB.updateBatchLoad( dataMap, "I", conn, userinfo );
//		
//		
//			if ( conn != null )
//			{
//				conn.close();
//				conn = null;
//			}
//			
//			String batchID = "";
//			String fileName = "";
//			String objName = "";
//			String subject = "";
//			String templateId = "";
//			String templateName = "";
//			String ediAddr = "";
//			String threadKey = "";
//			String dependency = "";
//			String addUser = "";
//			String loadStat = "";
//			String tranSlStr = "0";
//			int tranSl = 0;
//			
//			for( Map.Entry<Integer, HashMap<String, String>> dataEntry : dataMap.entrySet() )
//			{
//				
//				
//
//				HashMap<String, String> tempDataMap = dataEntry.getValue();
//				RestAPIServiceUtility restapiserviceutility = new RestAPIServiceUtility();
//				objName = restapiserviceutility.checkNull( tempDataMap.get( "WIN_NAME" ) );
//				objName = objName.substring( objName.indexOf("_") + 1 );
//				batchID = restapiserviceutility.checkNull( tempDataMap.get( "BATCH_ID" ) );
//				fileName = restapiserviceutility.checkNull( tempDataMap.get( "DATA_FILE_NAME" ) ); 
//				subject = restapiserviceutility.checkNull( tempDataMap.get( "SUBJECT" ) );
//				templateId = restapiserviceutility.checkNull( tempDataMap.get( "XFRM_TEMPLATE" ) );
//				templateName = restapiserviceutility.checkNull( tempDataMap.get( "TEMPLATE_NAME" ) );
//				//Added by Pooja S on 12-JAN-2021 [Batchload interface to store keyFieldValue for the transaction]
//				tranSlStr = restapiserviceutility.checkNull( tempDataMap.get( "TRAN_SL" ) );
//				if ( tranSlStr.length() > 0 )
//				{
//					tranSl = Integer.parseInt( tranSlStr );
//				}
//				ediAddr = restapiserviceutility.checkNull( tempDataMap.get( "EDI_ADDR" ) );
//				threadKey = restapiserviceutility.checkNull( tempDataMap.get( "THREAD_KEY" ) );
//				addUser = restapiserviceutility.checkNull( tempDataMap.get( "ADD_USER" ) ).trim();
//				loadStat = restapiserviceutility.checkNull( tempDataMap.get( "LOAD_STAT" ) );
//				
//				BaseLogger.log( "3", userinfo, null, "objName : ["+ objName +"]" );
//				BaseLogger.log( "3", userinfo, null, "batchID : ["+ batchID +"]" );
//				BaseLogger.log( "3", userinfo, null, "fileName : ["+ fileName +"]" );
//				BaseLogger.log( "3", userinfo, null, "subject : ["+ subject +"]" );
//				BaseLogger.log( "3", userinfo, null, "templateId : ["+ templateId +"]" );
//				BaseLogger.log( "3", userinfo, null, "templateName : ["+ templateName +"]" );
//				BaseLogger.log( "3", userinfo, null, "ediAddr : ["+ ediAddr +"]" );
//				BaseLogger.log( "3", userinfo, null, "threadKey : ["+ threadKey +"]" );
//				BaseLogger.log( "3", userinfo, null, "addUser : ["+ addUser +"]" );
//				BaseLogger.log( "3", userinfo, null, "loadStat : ["+ loadStat +"]" );
//				
//				if ( fileName.length() == 0 || fileName.indexOf( "." ) == -1 )
//				{
//					continue;
//				}
//				dependency = "";
//				threadKey = restapiserviceutility.checkNull( threadKey );
//				if ( threadKey.length() > 0 )
//				{
//					dependency = getDBAccess().getDBColumnValue( "BATCHLOAD", "(BATCH_ID || ':' || TRAN_SL)~AS~DEPENDENCY", (" THREAD_KEY = '"+ threadKey +"' AND LOAD_STAT = 'E' "), userinfo.getTransDB() );
//				}
//				dependency = restapiserviceutility.checkNull( dependency );
//				if ( dependency.length() > 0 )
//				{
//					//Changed by Ravindra C on 17-07-21 to update the load_stat As a N. - Start
//					//getDBAccess().updateTableColumnValue( "BATCHLOAD", "DEPENDENCY", dependency, (" BATCH_ID = '" + batchID + "' AND TRAN_SL = '"+ tranSl +"' "), userInfo.getTransDB() );
//					masterApplyEJB.updateBatchLoad( batchID, tranSl, loadStat, dependency, null, userinfo );
//					//Changed by Ravindra C on 17-07-21 to update the load_stat As a I. - End
//					continue;
//				}
//				else
//				{
//					String[] fileInfoArr = new String[6];
//					fileInfoArr[0] = "false";
//					fileInfoArr[1] = fileName;
//					fileInfoArr[2] = objName;
//					fileInfoArr[3] = "";
//					fileInfoArr[4] = templateName;
//					fileInfoArr[5] = subject;
//					//fileInfoArr[7] = "true"; //isRetXML
//					
//					String fileType = fileName.substring( fileName.lastIndexOf(".") + 1 );
//					BaseLogger.log( "3", userinfo, null, "fileType : ["+ fileType +"]" );
//					String uploadFilePath = "";
//					String dataDumpFolderName = "";
//					if( "json".equalsIgnoreCase( fileType ) )
//					{
//						dataDumpFolderName = "JSON_UPLOAD";
//					}
//					else
//					{
//						dataDumpFolderName = "XLS_UPLOAD";
//						fileType = "xml";
//					}
//
//					uploadFilePath = CommonConstants.JBOSSHOME + File.separator + dataDumpFolderName + File.separator + addUser + File.separator + batchID;
//					File DUMP_DIR = null;
//					DUMP_DIR = new File( uploadFilePath );
//					if ( ! DUMP_DIR.exists() )
//					{
//						DUMP_DIR.mkdirs();
//					}
//					//Added by Ravindra C on 19/02/2021 [move failed file to load folder in case of reload] START
//					if( "R".equalsIgnoreCase( loadStat ) )
//					{
//						moveFailedFileToUpload( uploadFilePath, fileName );
//					}
//					//Added by Ravindra C on 19/02/2021 [move failed file to load folder in case of reload] END
//					
//
//					
//			
//
//					String inputdata = readUploadFailFileContents(batchID);
//
//					
//					// Changes by Gagan B. as per suggestions of Danish Sir to remove condition and pass inputData to writeFile method which is passed to transLoad as parameter.
//					new E12GenericUtility().writeFile( uploadFilePath, fileName, inputdata );
//					//new E12GenericUtility().writeFile( uploadFilePath, fileName + "GSB", inputData );
//					
//					ITMUploadFileEJB itmUploadFileEJB = new ITMUploadFileEJB();
//					//serviceConfigGlobal = serviceConfig;
//					result = itmUploadFileEJB.insertFileData( fileInfoArr, userInfo, DUMP_DIR, CommonConstants.APPLICATION_CONTEXT, "", false, false, batchID, tranSl );
//					
//					String messageFromBatchLoad = "";
//					BaseLogger.log("3",null,null,"batchId --> handleRequest:: " + batchId);
//					if (userInfo != null) 
//					{
//						DBAccessEJB dbAccessEJB = new DBAccessEJB();
//						try 
//						{
//							//Changes by Gagan B. to not retrieve value if ERROR_MSG column's value is null.
//							messageFromBatchLoad = dbAccessEJB.getDBColumnValue("BATCHLOAD", "ERROR_MSG", "BATCH_ID  = '"+batchId+"'" + "AND ERROR_MSG IS NOT NULL", userInfo.getTransDB());
//						} 
//						catch (RemoteException | ITMException e) 
//						{
//							e.printStackTrace();
//						}
//					}
//					//Added by Gagan B. for setDataAndConfirm endpoint functionality [START]
//					BaseLogger.log("3",null,null,"messageFromBatchLoad --> transLoad:: " + messageFromBatchLoad);
//					BaseLogger.log( "3", null, null, "result from transLoad gsb:::" +  result);
//					
//					String parentPKValues = itmUploadFileEJB.globalTranID;
//					PKValue = parentPKValues;
//					BaseLogger.log( "3", null, null, "parentPKValues from transLoad gsb:::" +  parentPKValues);
//					
//
//				}
//			
//				
//			}
//		
//		
//		
//		
//		
//		
//		}
//		
//		catch (SQLException e)
//		{
//			BaseLogger.log( "0", null, null, "SQLException :: from transLoad() : ["+ e.getMessage() +"]" );
//			e.printStackTrace();
//			throw new ITMException( e );
//			
//		}
//		
//		
//		catch (Exception e) 
//		{
//			BaseLogger.log( "0", null, null, "Exception :: from transLoad() : ["+ e.getMessage() +"]" );
//			e.printStackTrace();
//			throw new ITMException( e );
//		}
//		
//		
//		finally
//		{
//			try 
//			{
//				if ( rs != null )
//				{
//					rs.close();
//					rs = null;
//				}
//				if ( pstmt != null )
//				{
//					pstmt.close();
//					pstmt = null;
//				}
//				if ( conn != null )
//				{
//					conn.close();
//					conn = null;
//				}
//			}
//			catch (SQLException e) 
//			{
//				e.printStackTrace();
//			}
//		}
//		
//		
//		return result;
//	}
//	
	
	
	public String transReload(String appId, UserInfoBean userInfo, String batchId) throws ITMException 
	{
			String result = "";
			Connection conn = null;
			java.sql.PreparedStatement pstmt = null;
			ResultSet rs = null;
			String inputData = "";
			String PKValue = "";
			
			try 
			{
				ConnDriver connDriver = new ConnDriver();
				conn = connDriver.getConnectDB( userInfo.getTransDB() );
				connDriver = null;
				
				BaseLogger.log( "3", userInfo, null, "daniel batchload inside transload"+batchId );
				BaseLogger.log( "3", userInfo, null, "appId : ["+ appId +"]" );
				String appIdAddr = "";
				if ( appId.length() > 0 )
				{
					appIdAddr = (appId + "_");
					BaseLogger.log( "3", userInfo, null, "gsb appIdAddr : ["+ appIdAddr +"]" );
				}
				
				String sql = "SELECT BATCH.BATCH_ID, BATCH.WIN_NAME, BATCH.DATA_FILE_NAME, BATCH.SUBJECT, BATCH.XFRM_TEMPLATE, TEMPL.TEMPLATE_NAME, BATCH.TRAN_SL, BATCH.EDI_ADDR, BATCH.THREAD_KEY, BATCH.ADD_USER, BATCH.LOAD_STAT, TRAN.LOAD_ORDER, BATCH.LOAD_ORDER " + 
						" FROM TRANSETUP TRAN, BATCHLOAD BATCH LEFT OUTER JOIN OBJ_FILE_TEMPLATE TEMPL ON BATCH.XFRM_TEMPLATE = TEMPL.TEMPLATE_ID " + 
						" WHERE BATCH_ID = ? "+
						" AND BATCH.LOAD_STAT IN ( 'N', 'R', 'E' ) " +
						" AND TRAN.TRAN_WINDOW = BATCH.WIN_NAME " + 
						" AND BATCH.EDI_ADDR IS NOT NULL AND BATCH.EDI_ADDR IN ( '"+ appIdAddr +"fileSystem', '"+ ( appIdAddr + CommonConstants.API_FILE_DESTINATION ) +"' ) " + 
						" ORDER BY TRAN.LOAD_ORDER, BATCH.LOAD_ORDER, BATCH.ADD_DATE, BATCH.BATCH_ID, BATCH.TRAN_SL ";
				

				//String sql2 = "SELECT * FROM BATCHLOAD WHERE BATCH_ID = '"+batchId+"'  ";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, batchId);
				rs = pstmt.executeQuery();
				BaseLogger.log( "3", userInfo, null, "daniel sql  inside transload:  " + sql);
				BaseLogger.log("3",null,null,"DANiel BATCHid  transrelaod: " + batchId);

				
				HashMap<Integer, HashMap<String, String>> dataMap = new LinkedHashMap<Integer, HashMap<String,String>>();

				ResultSetMetaData rsmd = rs.getMetaData();
				int noOfColumns = rsmd.getColumnCount();
				BaseLogger.log( "3", userInfo, null, "daniel noOfColumns : "+noOfColumns );

				
				
				while( rs.next() )
				{
					BaseLogger.log( "3", userInfo, null, "daniel inside while loop" );
					HashMap<String, String> tempMap = new HashMap<String, String>();
					for(int ctr = 1; ctr <= noOfColumns; ctr++)
					{
						if( "mysql".equalsIgnoreCase( CommonConstants.DB_NAME ) )
						{
							tempMap.put( rsmd.getColumnName(ctr).toUpperCase(), rs.getString(ctr) );
						}
						else
						{
							tempMap.put( rsmd.getColumnName(ctr), rs.getString(ctr) );
							BaseLogger.log( "3", userInfo, null, "daniel inside while loop else part" );

						}
					}
					dataMap.put( 1, tempMap ); // Changed by Gagan B. for storing only latest transaction in map.
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;
				
				//Added By Ravindra C on 17-07-21 to update the load_stat As a I.
				MasterApplyEJB masterApplyEJB = new MasterApplyEJB();
				//masterApplyEJB.updateBatchLoad( dataMap, "I", conn, userInfo );
				
				if ( conn != null )
				{
					conn.close();
					conn = null;
				}
				BaseLogger.log( "3", userInfo, null, "daniel inside while loop else part" );

				String batchID = "";
				String fileName = "";
				String objName = "";
				String subject = "";
				String templateId = "";
				String templateName = "";
				String ediAddr = "";
				String threadKey = "";
				String dependency = "";
				String addUser = "";
				String loadStat = "";
				String tranSlStr = "0";
				int tranSl = 0;
				
				
				for( Map.Entry<Integer, HashMap<String, String>> dataEntry : dataMap.entrySet() )
				{
					BaseLogger.log( "3", userInfo, null, "daniel inside while loop else part" );

					HashMap<String, String> tempDataMap = dataEntry.getValue();
					RestAPIServiceUtility restapiserviceutility = new RestAPIServiceUtility();
					objName = restapiserviceutility.checkNull( tempDataMap.get( "WIN_NAME" ) );
					objName = objName.substring( objName.indexOf("_") + 1 );
					BaseLogger.log( "3", userInfo, null, "daniel inside while loop else part" );

					batchID = restapiserviceutility.checkNull( tempDataMap.get( "BATCH_ID" ) );
					fileName = restapiserviceutility.checkNull( tempDataMap.get( "DATA_FILE_NAME" ) ); 
					subject = restapiserviceutility.checkNull( tempDataMap.get( "SUBJECT" ) );
					BaseLogger.log( "3", userInfo, null, "daniel inside while loop else part" );
					templateId = restapiserviceutility.checkNull( tempDataMap.get( "XFRM_TEMPLATE" ) );
					templateName = restapiserviceutility.checkNull( tempDataMap.get( "TEMPLATE_NAME" ) );
					tranSlStr = restapiserviceutility.checkNull( tempDataMap.get( "TRAN_SL" ) );
					if ( tranSlStr.length() > 0 )
					{
						tranSl = Integer.parseInt( tranSlStr );
					}
					ediAddr = restapiserviceutility.checkNull( tempDataMap.get( "EDI_ADDR" ) );
					threadKey = restapiserviceutility.checkNull( tempDataMap.get( "THREAD_KEY" ) );
					BaseLogger.log( "3", userInfo, null, "daniel inside while loop else part" );

					addUser = restapiserviceutility.checkNull( tempDataMap.get( "ADD_USER" ) ).trim();
					loadStat = restapiserviceutility.checkNull( tempDataMap.get( "LOAD_STAT" ) );
					
					BaseLogger.log("3",null,null,"DANiel BATCHid INSIDE transrelaod: " + batchId);
					BaseLogger.log( "3", userInfo, null, "daniel objName : ["+ objName +"]" );
					BaseLogger.log( "3", userInfo, null, "dan batchID : ["+ batchID +"]" );
					BaseLogger.log( "3", userInfo, null, "fileName : ["+ fileName +"]" );
					BaseLogger.log( "3", userInfo, null, "subject : ["+ subject +"]" );
					BaseLogger.log( "3", userInfo, null, "templateId : ["+ templateId +"]" );
					BaseLogger.log( "3", userInfo, null, "templateName : ["+ templateName +"]" );
					BaseLogger.log( "3", userInfo, null, "dan ediAddr : ["+ ediAddr +"]" );
					BaseLogger.log( "3", userInfo, null, "threadKey : ["+ threadKey +"]" );
					BaseLogger.log( "3", userInfo, null, "addUser : ["+ addUser +"]" );
					BaseLogger.log( "3", userInfo, null, "daniel loadStat : ["+ loadStat +"]" );
					
					if ( fileName.length() == 0 || fileName.indexOf( "." ) == -1 )
					{
						continue;
					}
					dependency = "";
					threadKey = restapiserviceutility.checkNull( threadKey );
					if ( threadKey.length() > 0 )
					{
						dependency = getDBAccess().getDBColumnValue( "BATCHLOAD", "(BATCH_ID || ':' || TRAN_SL)~AS~DEPENDENCY", (" THREAD_KEY = '"+ threadKey +"' AND LOAD_STAT = 'E' "), userInfo.getTransDB() );
					}
					dependency = restapiserviceutility.checkNull( dependency );
					if ( dependency.length() > 0 )
					{
						//Changed by Ravindra C on 17-07-21 to update the load_stat As a N. - Start
						//getDBAccess().updateTableColumnValue( "BATCHLOAD", "DEPENDENCY", dependency, (" BATCH_ID = '" + batchID + "' AND TRAN_SL = '"+ tranSl +"' "), userInfo.getTransDB() );
						masterApplyEJB.updateBatchLoad( batchID, tranSl, loadStat, dependency, null, userInfo );
						//Changed by Ravindra C on 17-07-21 to update the load_stat As a I. - End
						continue;
					}
					else
					{
						String[] fileInfoArr = new String[6];
						fileInfoArr[0] = "false";
						fileInfoArr[1] = fileName;
						fileInfoArr[2] = objName;
						fileInfoArr[3] = "";
						fileInfoArr[4] = templateName;
						fileInfoArr[5] = subject;
						//fileInfoArr[7] = "true"; //isRetXML
						
						String fileType = fileName.substring( fileName.lastIndexOf(".") + 1 );
						BaseLogger.log( "3", userInfo, null, "fileType : ["+ fileType +"]" );
						String uploadFilePath = "";
						String dataDumpFolderName = "";
						if( "json".equalsIgnoreCase( fileType ) )
						{
							dataDumpFolderName = "JSON_UPLOAD";
						}
						else
						{
							dataDumpFolderName = "XLS_UPLOAD";
							fileType = "xml";
						}
						//Changed by Ravindra C on 19/02/2021 [set added user in path]
						//uploadFilePath = CommonConstants.JBOSSHOME + File.separator + dataDumpFolderName + File.separator + userInfo.getLoginCode() + File.separator + batchID;
						uploadFilePath = CommonConstants.JBOSSHOME + File.separator + dataDumpFolderName + File.separator + addUser + File.separator + batchID;
						File DUMP_DIR = null;
						DUMP_DIR = new File( uploadFilePath );
						if ( ! DUMP_DIR.exists() )
						{
							DUMP_DIR.mkdirs();
						}
						//Added by Ravindra C on 19/02/2021 [move failed file to load folder in case of reload] START
						if( "R".equalsIgnoreCase( loadStat ) )
						{
							moveFailedFileToUpload( uploadFilePath, fileName );
						}
						//Added by Ravindra C on 19/02/2021 [move failed file to load folder in case of reload] END
						
						
						
						DBAccessEJB dbacessEJb = new DBAccessEJB();
						
						fileName = dbacessEJb.getDBColumnValue("BATCHLOAD", "DATA_FILE_NAME", "BATCH_ID  = '"+batchID+"' ", userInfo.getTransDB());
						BaseLogger.log("3",null,null,"DANiel data_File_Name: " + fileName);
						
//						if(fileName.isEmpty() || fileName.trim().length() == 0 || fileName == null )
//							
//						{
//							errorString = itmDBAccessEJB.getErrorString("","FLNTFND",addUser,"",conn);
//						}
						
						
//						*************************daniel
						
						
//						
//						String filepath = "/wildfly/upload_failed/"+fileName;
//						BaseLogger.log("3",null,null,"DANiel filepath: " + filepath);
//
//						BufferedReader bufferreader = new BufferedReader(new FileReader(filepath));
//						StringBuilder sb = new StringBuilder();
//						String line = bufferreader.readLine();
//						
//						while(line != null)
//						{
//							sb.append(line);
//							line = bufferreader.readLine();
//						}
//						
//						 	inputData = sb.toString();
//							BaseLogger.log("3",null,null,"DANiel input: " + inputData);
//							BaseLogger.log("3",null,null,"DANiel StringBuilder sb: " + sb);
						
							
//							************daniel
					
						String inputdata = readUploadFailFileContents(batchID);
						BaseLogger.log("3",null,null,"daniel inputdata from readuploafail method" + inputdata);

						
//						***daniel
						
						// Changes by Gagan B. as per suggestions of Danish Sir to remove condition and pass inputData to writeFile method which is passed to transLoad as parameter.
						new E12GenericUtility().writeFile( uploadFilePath, fileName, inputdata );
						//new E12GenericUtility().writeFile( uploadFilePath, fileName + "GSB", inputData );
						BaseLogger.log("3",null,null,"daniel below writefile method " + batchId);

						ITMUploadFileEJB itmUploadFileEJB = new ITMUploadFileEJB();
						result = itmUploadFileEJB.insertFileData( fileInfoArr, userInfo, DUMP_DIR, CommonConstants.APPLICATION_CONTEXT, "", false, false, batchID, tranSl );
						
						BaseLogger.log("3",null,null,"daniel result from inserdatafile method" + batchId);

						
						String messageFromBatchLoad = "";
						BaseLogger.log("3",null,null,"batchId --> handleRequest:: " + batchId);
						if (userInfo != null) 
						{
							DBAccessEJB dbAccessEJB = new DBAccessEJB();
							try 
							{
								//Changes by Gagan B. to not retrieve value if ERROR_MSG column's value is null.
								messageFromBatchLoad = dbAccessEJB.getDBColumnValue("BATCHLOAD", "ERROR_MSG", "BATCH_ID  = '"+batchId+"'" + "AND ERROR_MSG IS NOT NULL", userInfo.getTransDB());
							} 
							catch (RemoteException | ITMException e) 
							{
								e.printStackTrace();
							}
						}
						//Added by Gagan B. for setDataAndConfirm endpoint functionality [START]
						BaseLogger.log("3",null,null,"messageFromBatchLoad --> transLoad:: " + messageFromBatchLoad);
						BaseLogger.log( "3", null, null, "result from transLoad gsb:::" +  result);
						
						String parentPKValues = itmUploadFileEJB.globalTranID;
						PKValue = parentPKValues;
						BaseLogger.log( "3", null, null, "parentPKValues from transLoad gsb:::" +  parentPKValues);
						
					}
				}
			}
			catch (SQLException e) 
			{
				BaseLogger.log( "0", null, null, "SQLException :: from transLoad() : ["+ e.getMessage() +"]" );
				e.printStackTrace();
				throw new ITMException( e );
			}
			catch (Exception e) 
			{
				BaseLogger.log( "0", null, null, "Exception :: from transLoad() : ["+ e.getMessage() +"]" );
				e.printStackTrace();
				throw new ITMException( e );
			}
			finally
			{
				try 
				{
					if ( rs != null )
					{
						rs.close();
						rs = null;
					}
					if ( pstmt != null )
					{
						pstmt.close();
						pstmt = null;
					}
					if ( conn != null )
					{
						conn.close();
						conn = null;
					}
				}
				catch (SQLException e) 
				{
					e.printStackTrace();
				}
			}
			return result;
	}
	
	
	private void moveFailedFileToUpload( String uploadFilePath, String fileName )
	{
		String commonUploadSuccessFilePath = ( new File( CommonConstants.UPLOAD_LOC ) ) + File.separator + "upload_success";
		String commonUploadFailedFilePath = ( new File( CommonConstants.UPLOAD_LOC ) ) + File.separator + "upload_failed";
		File file = new File( commonUploadFailedFilePath + File.separator + fileName );
		if ( file.exists() )
		{
			File dir = new File( uploadFilePath );
			if ( ! dir.exists() )
			{
				dir.mkdirs();
			}
			BaseLogger.log( "3", userInfo, null, "dir --> ["+ dir +"]" );
			boolean success = file.renameTo( new File( dir, file.getName() ) );
			if ( ! success )
			{
				BaseLogger.log( "3", userInfo, null, "File was not moved" );
			}
		}
		else
		{
			BaseLogger.log( "3", userInfo, null, "File not exist In the failed path" );
			
			file = new File( commonUploadSuccessFilePath + File.separator + fileName );
			if ( file.exists() )
			{
				File dir = new File( uploadFilePath );
				if ( ! dir.exists() )
				{
					dir.mkdirs();
				}
				BaseLogger.log( "3", userInfo, null, "dir --> ["+ dir +"]" );
				boolean success = file.renameTo( new File( dir, file.getName() ) );
				if ( ! success )
				{
					BaseLogger.log( "3", userInfo, null, "File was not moved" );
				}
			}
		}
	}
	
	
	private DBAccessEJB getDBAccess()
	{
		DBAccessEJB dbAccess = null;
		try 
		{
			if ( dbAccess == null )
			{
				//AppConnectParm appConnect = new AppConnectParm();
				//InitialContext initialContext = new InitialContext(appConnect.getProperty());

				//dbAccess = (DBAccessLocal) initialContext.lookup("ibase/DBAccessEJB/local");
				dbAccess = new DBAccessEJB();
			}
		}
		/*catch (NamingException e) 
		{
			e.printStackTrace();
		}*/
		catch (Exception e) 
		{
			e.printStackTrace();
		}

		return dbAccess;
	}
	
	
}
