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.SQLException;

import com.mysql.jdbc.PreparedStatement;

import ibase.utility.BaseLogger;
import ibase.utility.CommonConstants;
import ibase.webitm.ejb.ActionHandlerEJB;
import ibase.webitm.ejb.DBAccessEJB;
import ibase.webitm.ejb.ITMDBAccessEJB;
import ibase.webitm.utility.ITMException;
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
{
	@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);
			

			
//			VisionEDIUtility visionediutility = new VisionEDIUtility();
//			visionediutility.transLoad(appId, getUserInfo(), "", "");
			
			
//			******************DANIEL changes

	        errString = readFileContents(batchid,appId);
//	        BaseLogger.log("3",null,null,"DANIEL input" + input);

//***************
			
			
			//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;
	}
	
	public String readFileContents(String batchID,String appId) throws RemoteException, ITMException, SQLException
	{
		
		
		String input = "",fileName="",filepath ="",errorString="";
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
		Connection conn = getConnection();


		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 appId: " + appId);
			BaseLogger.log("3",null,null,"DANiel loadstat: " + loadstat);
			BaseLogger.log("3",null,null,"DANiel batchID: " + batchID);

			if("E".equalsIgnoreCase(loadstat))
			//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 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,"DANiel appId: " + appId);
					//loadstat ="R";
					
//					String sql = "update batchload \n"
//							+ "set load_stat = 'R'\n"
//							+ "where batch_id =";
					
					String sql = "UPDATE BATCHLOAD SET LOAD_STAT = 'R' WHERE BATCH_ID = '"+batchID+ "' ";
					java.sql.PreparedStatement 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);

					
					errorString = itmDBAccessEJB.getErrorString("","RLOADSUC",addUser,"",conn);
					//errorString = itmDBAccessEJB.getErrorString("","RLOADFAIL",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;
				
				}
				
				
			}
			
			catch (Exception e) {
				
				e.printStackTrace();
				System.out.println("EXception is"+e);
			}
				
		}
		BaseLogger.log("3",null,null,"DANiel errorString: " + errorString);
		return errorString;
	}
	
	
}
