package com.bankaudit.rest.process.controller;

import java.nio.charset.Charset;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.InternalServerErrorException;

import org.jboss.logging.Logger;
import org.json.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.client.UnknownHttpStatusCodeException;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.bankaudit.constants.BankAuditConstant;
import com.bankaudit.dto.DataTableResponse;
import com.bankaudit.dto.process.AuditLevelDocumentDetailsDto;
import com.bankaudit.dto.process.IfcEnsureBaasInterfaceDto;
import com.bankaudit.process.model.AuditLevelDocumentDetails;
import com.bankaudit.rest.process.service.AuditRatingParameterScoreService;
import com.bankaudit.rest.process.service.AuditScheduleService;
import com.bankaudit.rest.process.service.IfcDataOfflineUploadService;
import com.bankaudit.rest.process.service.IfcEnsureBaasDataService;
import com.bankaudit.rest.process.service.MyAuditsService;
import com.bankaudit.service.MaintEntityService;
import com.bankaudit.service.UserService;
import com.bankaudit.util.BankAuditUtil;
import com.bankaudit.util.ServiceStatus;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;



@RestController

@RequestMapping("/api/ifcEnsureBaasInterface")
public class IfcEnsureBaasInterfaceController {
	 
	@Autowired
	IfcEnsureBaasDataService  ifcEnsureBaasDataService;
	
	@Autowired
	IfcDataOfflineUploadService  ifcEnsureBaasDataOfflineUploadService;
	
	@Autowired
	MyAuditsService  myAuditsService;	
	
	@Autowired
	MaintEntityService maintEntityService;	
	
	
		
	static final Logger logger = Logger.getLogger(IfcEnsureBaasInterfaceController.class);	
	
	static RestTemplate restTemplate = new RestTemplate();
	private String functionId="ifcEnsureBaasData";
	
	static String baseUri="http://dcmsuatapi.nabard.org/DCMS_API/";
	static String apiKey="1a2d7e42-c178-4b62-bcaa-383a47cbec6e";
	static String version="2";
	
	   // PARAMETER-1 =>License code => Unit Code
	   // PARAMETER-2 =>Inspection Type => RRB/StCB/DCCB
	   // PARAMETER-3 =>Financial Year
	   // PARAMETER-4 =>Annual/Bi-annual
	   // PARAMETER-5 =>Document Name => Appendix I ot IV / Appendix VIII / Appendix VII / Annexure to RN / Annexure to RN Enhanced CAMELSC/ Annexure to RN
	
	/** Method used for IRCSV and RatingCSV **/
		
@RequestMapping(value="/fetchAuditLevelIRCSVDocument" ,method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
		ServiceStatus  fetchAuditLevelCSVDocuments(
				@RequestParam(value="maker")String maker, 
				@RequestParam(value="role")String role,
				@RequestParam(value="legalEntityCode")Integer legalEntityCode,
				@RequestParam(value="auditTypeCode")String auditTypeCode, 
				@RequestParam(value="auditId")String auditId, 
				@RequestParam(value="planId")String planId, 
				@RequestParam(value="documentType")String documentType,
				@RequestParam(value="warningCheck")String warningCheck, 
				@RequestParam(value="documentName")String  documentName,
				@RequestParam(value="unitCode")String  unitCode,
				@RequestParam(value="documentFetchType")String  documentFetchType,
				@RequestParam(value="inspectionFrequency")String  inspectionFrequency,
				@RequestParam(value="seqId", required=false)String seqId)  {
			
			ServiceStatus serviceStatus=new ServiceStatus();
			 
			try {
				logger.info("Inside fetchAuditLevelIRCSVDocument .. "+ auditId+" .. "+unitCode+" .. "+auditTypeCode+" DocType ::"+documentType+" DocName ::"+documentName+" DoCFetchType ::"+documentFetchType+" InspectionFrequency ::"+inspectionFrequency);
				String extApi=null;
				String unitCodeP1=maintEntityService.getLicenseeCodeForUnitCode(legalEntityCode, unitCode);  // License Code
				String financialYearP3=myAuditsService.getFinancialYearByAuditId(legalEntityCode, auditTypeCode, auditId);
				String auditTypeCodeP2=(auditTypeCode.contains("RRB")?"RRB":(auditTypeCode.contains("StCB")?"StCB":(auditTypeCode.contains("DCCB")?"DCCB":auditTypeCode)));
				int inspectionFrequencyP4=Integer.parseInt(inspectionFrequency);
				if(!auditTypeCode.contains("DCCB")) inspectionFrequencyP4=1;
				
				if("IRPartAB".equalsIgnoreCase(documentType) && "IR".equalsIgnoreCase(documentName)) {
					extApi="api/SuperSoft/CrisMAc/InspectionCSV";
				}else if("RatingCSV".equalsIgnoreCase(documentType) && "PARAM_RATING".equalsIgnoreCase(documentName)) {
					extApi="/api/SuperSoft/CrisMAc/RatingCSV";
				}
				
				HttpHeaders headers = new HttpHeaders();

				logger.info("CSV Req Values ..=>"+ baseUri+extApi +" P1::"+unitCodeP1+" P2::"+ auditTypeCodeP2 +" P3::"+financialYearP3+"p4::"+inspectionFrequencyP4);
				
				
				// ******************************* Rest Call, Starts here *****************************************************//
				
				//methods of HttpHeaders to set additional information
				headers.setContentType(MediaType.APPLICATION_JSON); // set content-type and other headers
				headers.set("APIKey",apiKey);
				headers.set("version",version);
				
				logger.info("headers ..=>"+ headers);
				
				// request body parameters
				JSONObject ensureRequest = new JSONObject();
				ensureRequest.put("licensee_Code", unitCodeP1);
				ensureRequest.put("licensee_Subtype", auditTypeCodeP2);
				ensureRequest.put("financial_Year", financialYearP3);
				ensureRequest.put("inspection_Frequency", inspectionFrequencyP4);
				
				logger.info("ensureRequest ..=>"+ ensureRequest);
				
				// convert your request body to JSON formatted string using writeValueAsString() method of ObjectMapper 
				//String reqBodyData = new ObjectMapper().writeValueAsString(ensureRequest); 
				
				//logger.info("reqBodyData ..=>"+ reqBodyData);
				
				// build the request
				//HttpEntity<JSONObject> requestEnty = new HttpEntity<>(ensureRequest, headers);
				HttpEntity<String> requestEnty = new HttpEntity<String>(ensureRequest.toString(), headers);
				
				logger.info("requestEnty ..=>"+ requestEnty);
				
				restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
				
				// send POST request
		        //ResponseEntity<String> response = restTemplate.postForEntity(baseUri+extApi, requestEnty, String.class);
				ResponseEntity<Object> response = restTemplate.exchange(baseUri+extApi,HttpMethod.POST, requestEnty, Object.class);
		        
		        logger.info("response ..=>"+ response);
		        logger.info("response getBody()..=>"+ response.getBody());
		        logger.info("response getStatusCode()..=>"+ response.getStatusCode());

				/*String respBody=response.getBody().toString();
				respBody=respBody.replace("{", "{\"").replace("=", "\":\"").replace(", ", "\",\"").replace("}", "\"}");
				respBody=respBody.replace(":\"{\"", ": {\"").replace("\"}\",", "\"},");
				logger.info("respBody JSONObj .. "+respBody);*/
		        
				
				// check response
		        if (response.getStatusCode() == HttpStatus.OK) {
		        	logger.info("Request Successful");
		        	
		        	String respBody=BankAuditUtil.convertStringToJSONObjectReadable(response.getBody().toString());
		            
		            org.json.simple.JSONObject jObj = (org.json.simple.JSONObject) JSONValue.parse(respBody);  
		            logger.info("jObj .. "+jObj);
		            String state = (String) jObj.get("state");
		            String msg = (String) jObj.get("msg");
		            String data = (String) jObj.get("data");
		            String userType = (String) jObj.get("userType");
		            
		            org.json.simple.JSONObject results=(org.json.simple.JSONObject)jObj.get("results");
		            String resStaus = (String) results.get("status");
		            String resMsg = (String) results.get("msg");
		            String resUserType = (String) results.get("userType");
		            
		            logger.info("state::"+state +" msg::"+msg+" userType::"+userType +" resStatus::"+resStaus+" resMsg::"+resMsg+" resUserType::"+resUserType);
		            logger.info("data=>CSV file path::"+data);
		            
		            String fileName=(data!=null?data.split("\\\\")[2]:data);  // (data!=null?data.split("\\\\")[2].split("\\.")[0]:data)
		            logger.info("fileName .."+fileName);
		           
		            IfcEnsureBaasInterfaceDto ifcDto=new IfcEnsureBaasInterfaceDto();
		            ifcDto.setAuditId(auditId);
		            ifcDto.setAuditTypeCode(auditTypeCode);
		            ifcDto.setUnitId(unitCode);
		            ifcDto.setDocumentType(documentType);
		            ifcDto.setDocumentName(documentName);
		            ifcDto.setFileName(fileName);
		             
		            //logger.info(response.getBody());
		            //JSONParser parser=new JSONParser();
		            //org.json.simple.JSONObject jsonObject1=(org.json.simple.JSONObject) parser.parse(response.getBody().toString());
		            //logger.info("jsonObject1  .... => "+ jsonObject1);
		            
		            if("200".equals(resStaus)){
						serviceStatus.setResult(ifcDto);
						serviceStatus.setStatus("success");
						serviceStatus.setMessage("CSV Generated Successfully.");
					}else if("600".equals(resStaus)){
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("The requested file is not present.");
					}else if("601".equals(resStaus)){
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("The header is missing.");
					}else if("400".equals(resStaus)){
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("Bad request.");
					}else if("401".equals(resStaus)){
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("Unauthorized access");
					}else if("403".equals(resStaus)){
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("Forbidden request");
					}else{
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage(resStaus);
					}
		            
		        } else {
		        	logger.info("Request Failed");
		        	logger.info(response.getStatusCode());
		        }
				/***************************************** Rest Call, End here ***************************************/
				
				
				/**************** Only for SIT, Testing  *****************/
				/*IfcEnsureBaasInterfaceDto ifcDto=new IfcEnsureBaasInterfaceDto();
	            ifcDto.setAuditId(auditId);
	            ifcDto.setAuditTypeCode(auditTypeCode);
	            ifcDto.setUnitId(unitCode);
	            ifcDto.setDocumentType(documentType);
	            ifcDto.setDocumentName(documentName);
	            ifcDto.setFileName("TS_Inspection Report CSV_RRB_1_24022025183023.csv");
	            
	            serviceStatus.setResult(ifcDto);
				serviceStatus.setStatus("success");
				serviceStatus.setMessage("CSV Generated Successfully ");*/
				
				/*************** SIT Testing, to comment *******************/
			} catch (Exception e) {
				e.printStackTrace(System.out);
				if (e instanceof InternalServerErrorException) {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("The ENSURE server is not reachable.");
		        }
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
			return serviceStatus;
		}		 
		
				
		/** Method used for Appendix and Annexure **/
		
@RequestMapping(value="/fetchAuditLevelAppendix" ,method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
		ServiceStatus  fetchAuditLevelAppendix(
				@RequestParam(value="maker")String maker, 
				@RequestParam(value="role")String role,
				@RequestParam(value="legalEntityCode")Integer legalEntityCode,
				@RequestParam(value="auditTypeCode")String auditTypeCode, 
				@RequestParam(value="auditId")String auditId, 
				@RequestParam(value="planId")String planId, 
				@RequestParam(value="documentType")String documentType,
				@RequestParam(value="warningCheck")String warningCheck, 
				@RequestParam(value="documentName")String  documentName,
				@RequestParam(value="unitCode")String  unitCode,
				@RequestParam(value="documentFetchType")String  docFetchType,
				@RequestParam(value="inspectionFrequency")String  inspectionFrequency,
				@RequestParam(value="seqId", required=false)String  seqId)  {
			
			ServiceStatus serviceStatus=new ServiceStatus();
			 
			try {
				logger.info("Inside fetchAuditLevelAppendix .. "+ auditId+" .. "+auditTypeCode+" DocType ::"+documentType+" DocName ::"+documentName+" DocFetchType ::"+docFetchType+" InspectionFrequency ::"+inspectionFrequency);
				String extApi="api/SuperSoft/CrisMAc/AppendixPDF";
				String unitCodeP1=maintEntityService.getLicenseeCodeForUnitCode(legalEntityCode, unitCode);  // License Code
				String financialYearP3=myAuditsService.getFinancialYearByAuditId(legalEntityCode, auditTypeCode, auditId);
				String auditTypeCodeP2=(auditTypeCode.contains("RRB")?"RRB":(auditTypeCode.contains("StCB")?"StCB":(auditTypeCode.contains("DCCB")?"DCCB":auditTypeCode)));
				String nameOfPdfFileP5=(docFetchType.equalsIgnoreCase("IRPartC_Apx_IV")?"APPENDIX_I_TO_IV":
						(docFetchType.equalsIgnoreCase("IRPartC_Apx_VII")?"APPENDIX_VII":(docFetchType.equalsIgnoreCase("IRPartC_Apx_VIII")?"APPENDIX_VIII":docFetchType)));
				int inspectionFrequencyP4=Integer.parseInt(inspectionFrequency);
				if(!auditTypeCode.contains("DCCB")) inspectionFrequencyP4=1;
				
				if("RN".equalsIgnoreCase(documentType) && auditTypeCode.contains("BEI")) {  // RRBEI, DCCBEI, StCBEI
					nameOfPdfFileP5="ANNEXURE_TO_RN_ENHANCED_CAMELSC";					
				}else if("RN".equalsIgnoreCase(documentType)) {  // DCCBI, StCBI
					nameOfPdfFileP5="ANNEXURE_TO_RN";
				}else if("LoSC".equalsIgnoreCase(documentType)) {  
					nameOfPdfFileP5="ANNEXURE_TO_LOSC";
				}
				
				if("RN".equalsIgnoreCase(documentType) || "LoSC".equalsIgnoreCase(documentType)) {
					extApi="api/SuperSoft/CrisMAc/AnnexurePDF";
				}
				
				
				
				HttpHeaders headers = new HttpHeaders();

				logger.info("PDF Values ..=>"+ baseUri+extApi +" P1::"+unitCodeP1+" P2::"+ auditTypeCodeP2 +" P3::"+financialYearP3+"P4::"+inspectionFrequencyP4);
				logger.info(" P5 => PDF File name "+nameOfPdfFileP5);
				
				// ******************************* Rest Call, Starts here *****************************************************//
				
				//methods of HttpHeaders to set additional information
				headers.setContentType(MediaType.APPLICATION_JSON); // set content-type and other headers
				headers.set("APIKey",apiKey);
				headers.set("version",version);
				
				logger.info("headers ..=>"+ headers);
				
				// request body parameters
				JSONObject ensureRequest = new JSONObject();
				ensureRequest.put("licensee_Code", unitCodeP1);
				ensureRequest.put("licensee_Subtype", auditTypeCodeP2);
				ensureRequest.put("financial_Year", financialYearP3);
				ensureRequest.put("inspection_Frequency", inspectionFrequencyP4);
				ensureRequest.put("name_of_the_PDF_file", nameOfPdfFileP5);
				
				logger.info("ensureRequest ..=>"+ ensureRequest);
				
				// convert your request body to JSON formatted string using writeValueAsString() method of ObjectMapper 
				//String reqBodyData = new ObjectMapper().writeValueAsString(ensureRequest); 
				
				//logger.info("reqBodyData ..=>"+ reqBodyData);
				
				// build the request
				//HttpEntity<JSONObject> requestEnty = new HttpEntity<>(ensureRequest, headers);
				HttpEntity<String> requestEnty = new HttpEntity<String>(ensureRequest.toString(), headers);
				
				logger.info("requestEnty ....=>"+ requestEnty);
				
				restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
				
				ResponseEntity<Object> response=null;
				String respStatusCode=null;
				try {
					// send POST request
			        //ResponseEntity<String> response = restTemplate.postForEntity(baseUri+extApi, requestEnty, String.class);
					response = restTemplate.exchange(baseUri+extApi,HttpMethod.POST, requestEnty, Object.class);
				}catch(HttpStatusCodeException e) {
					logger.info("HttpStatusCodeException ..=>"+ e.getRawStatusCode());
					respStatusCode=String.valueOf(e.getRawStatusCode());
				    ResponseEntity.status(e.getRawStatusCode()).headers(e.getResponseHeaders())
				                .body(e.getResponseBodyAsString());
				}catch(UnknownHttpStatusCodeException u) {
					logger.info("UnknownHttpStatusCodeException ..=>"+ u.getRawStatusCode());
					respStatusCode=String.valueOf(u.getRawStatusCode());
				    ResponseEntity.status(u.getRawStatusCode()).headers(u.getResponseHeaders())
				                .body(u.getResponseBodyAsString());
				}catch(Exception e) {
					logger.info("Exception e ..=>"+ e.getMessage());
				}     
				
			    logger.info("response ..=>"+ response);
			    if(response!=null) {
			    	logger.info("response getBody()..=>"+ response.getBody());
			    	logger.info("response getStatusCode()..=>"+ response.getStatusCode());
			    }
			        
	
					/*String respBody=response.getBody().toString();
					respBody=respBody.replace("{", "{\"").replace("=", "\":\"").replace(", ", "\",\"").replace("}", "\"}");
					respBody=respBody.replace(":\"{\"", ": {\"").replace("\"}\",", "\"},");
					logger.info("respBody JSONObj .. "+respBody);*/
			        
					
					// check response
			        if (response!=null && response.getStatusCode() == HttpStatus.OK) {
			        	logger.info("Request Successful");
			        	
			        	String respBody=BankAuditUtil.convertStringToJSONObjectReadable(response.getBody().toString());
			            
			            org.json.simple.JSONObject jObj = (org.json.simple.JSONObject) JSONValue.parse(respBody);  
			            logger.info("jObj .. "+jObj);
			            String state = (String) jObj.get("state");
			            String msg = (String) jObj.get("msg");
			            String data = (String) jObj.get("data");
			            String userType = (String) jObj.get("userType");
			            
			            org.json.simple.JSONObject results=(org.json.simple.JSONObject)jObj.get("results");
			            String resStaus = (String) results.get("status");
			            String resMsg = (String) results.get("msg");
			            String resUserType = (String) results.get("userType");
			            
			            logger.info("state::"+state +" msg::"+msg+" userType::"+userType +" resStatus::"+resStaus+" resMsg::"+resMsg+" resUserType::"+resUserType);
			            logger.info("data=>PDF file path::"+data);
			            
			            //String fileName=(data!=null?data.split("\\\\")[2]:data);
			            String fileName=(data!=null?data.split("\\\\")[2]:data);  // (data!=null?data.split("\\\\")[2].split("\\.")[0]:data)   // now using the file extension as well
			            logger.info("fileName .."+fileName);
			           
			            IfcEnsureBaasInterfaceDto ifcDto=new IfcEnsureBaasInterfaceDto();
			            ifcDto.setAuditId(auditId);
			            ifcDto.setAuditTypeCode(auditTypeCode);
			            ifcDto.setUnitId(unitCode);
			            ifcDto.setDocumentType(documentType);
			            ifcDto.setDocumentName(documentName);
			            ifcDto.setFileName(fileName);
			             
			            //logger.info(response.getBody());
			            //JSONParser parser=new JSONParser();
			            //org.json.simple.JSONObject jsonObject1=(org.json.simple.JSONObject) parser.parse(response.getBody().toString());
			            //logger.info("jsonObject1  .... => "+ jsonObject1);
			            
			            if("200".equals(resStaus)){
							serviceStatus.setResult(ifcDto);
							serviceStatus.setStatus("success");
							serviceStatus.setMessage("PDF Fetched Successfully ");
						}else if("600".equals(resStaus)){
							serviceStatus.setStatus("failure");
							serviceStatus.setMessage("The requested file is not present.");
						}else if("601".equals(resStaus)){
							serviceStatus.setStatus("failure");
							serviceStatus.setMessage("The header is missing.");
						}else if("400".equals(resStaus)){
							serviceStatus.setStatus("failure");
							serviceStatus.setMessage("Bad request.");
						}else if("401".equals(resStaus)){
							serviceStatus.setStatus("failure");
							serviceStatus.setMessage("Unauthorized access");
						}else if("403".equals(resStaus)){
							serviceStatus.setStatus("failure");
							serviceStatus.setMessage("Forbidden request");
						}else{
							serviceStatus.setStatus("failure");
							serviceStatus.setMessage(resStaus);
						}
			            
			        } else {
			        	logger.info("Request Failed");
			        	//IfcEnsureBaasInterfaceDto ifcDto=new IfcEnsureBaasInterfaceDto();
			        	//serviceStatus.setResult(ifcDto);
			        	serviceStatus.setStatus("failure");
			        	if("600".equals(respStatusCode))
			        		serviceStatus.setMessage("PDF Export Failed");
			        }
				/*}catch(UnknownHttpStatusCodeException u) {
					logger.info("UnknownHttpStatusCodeException .. "+u.getRawStatusCode());
					u.printStackTrace(System.out);
					if("600".equals(u.getRawStatusCode())) {
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("PDF Export failed.");
					}
				}*/
				/***************************************** Rest Call, End here ***************************************/
				
				
				/**************** Only for SIT, Testing  *****************/
				/*IfcEnsureBaasInterfaceDto ifcDto=new IfcEnsureBaasInterfaceDto();
	            ifcDto.setAuditId(auditId);
	            ifcDto.setAuditTypeCode(auditTypeCode);
	            ifcDto.setUnitId(unitCode);
	            ifcDto.setDocumentType(documentType);
	            ifcDto.setDocumentName(documentName);
	            ifcDto.setFileName("TS_Inspection Report CSV_RRB_1_24022025183023.csv");
	            
	            serviceStatus.setResult(ifcDto);
				serviceStatus.setStatus("success");
				serviceStatus.setMessage("CSV Generated Successfully ");*/
				
				/*************** SIT Testing, to comment *******************/
			} catch (Exception e) {
				e.printStackTrace(System.out);
				if (e instanceof InternalServerErrorException) {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("The ENSURE server is not reachable.");
		        }
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
				
			}
			return serviceStatus;
		}
		
		
@RequestMapping(value="/fetchAuditLevelAnnexure" ,method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
		ServiceStatus  fetchAuditLevelAnnexure(
				@RequestParam(value="maker")String maker, 
				@RequestParam(value="role")String role,
				// @RequestParam(value="files")CommonsMultipartFile[]  files,
				@RequestParam(value="legalEntityCode")Integer legalEntityCode,
				@RequestParam(value="auditTypeCode")String auditTypeCode, 
				@RequestParam(value="auditId")String auditId, 
				@RequestParam(value="planId")String planId, 
				@RequestParam(value="documentType")String documentType,
				@RequestParam(value="warningCheck")String warningCheck, 
				@RequestParam(value="documentName")String  documentName,
				@RequestParam(value="unitCode")String  unitCode,
				@RequestParam(value="seqId")String  seqId)  {
			
			ServiceStatus serviceStatus=new ServiceStatus();
			 
			try {
				logger.info("Inside fetchAuditLevelAnnexure .. "+ auditId+" .. "+auditTypeCode+" DocType ::"+documentType+" DocName ::"+documentName);
				String extApi="api/SuperSoft/CrisMAc/AnnexurePDF";
				String unitCodeP1=unitCode;  // License Code
				String financialYearP3=myAuditsService.getFinancialYearByAuditId(legalEntityCode, auditTypeCode, auditId);
				String auditTypeCodeP2=(auditTypeCode.contains("RRB")?"RRB":(auditTypeCode.contains("StCB")?"StCB":(auditTypeCode.contains("DCCB")?"DCCB":auditTypeCode)));
				String nameOfPdfFileP5=null;
				
				if("RN".equalsIgnoreCase(documentType) && auditTypeCode.contains("BEI")) {  // RRBEI, DCCBEI, StCBEI
					nameOfPdfFileP5="ANNEXURE_TO_RN";
				}else if("RN".equalsIgnoreCase(documentType)) {  // DCCBI, StCBI
					nameOfPdfFileP5="ANNEXURE_TO_RN_ENHANCED_CAMELSC";
				}else if("LoSC".equalsIgnoreCase(documentType)) {  
					nameOfPdfFileP5="ANNEXURE_TO_LOSC";
				}
				
				HttpHeaders headers = new HttpHeaders();

				logger.info("Values ..=>"+ baseUri+extApi +" .. "+unitCodeP1+" .. "+ auditTypeCodeP2 +" .. "+financialYearP3);
				
				
				// ******************************* Rest Call, Starts here *****************************************************//
				
				//methods of HttpHeaders to set additional information
				headers.setContentType(MediaType.APPLICATION_JSON); // set content-type and other headers
				headers.set("APIKey",apiKey);
				headers.set("version",version);
				
				logger.info("headers ..=>"+ headers);
				
				// request body parameters
				JSONObject ensureRequest = new JSONObject();
				ensureRequest.put("licensee_Code", unitCodeP1);
				ensureRequest.put("licensee_Subtype", auditTypeCodeP2);
				ensureRequest.put("financial_Year", financialYearP3);
				ensureRequest.put("inspection_Frequency", 1);
				
				logger.info("ensureRequest ..=>"+ ensureRequest);
				
				// convert your request body to JSON formatted string using writeValueAsString() method of ObjectMapper 
				//String reqBodyData = new ObjectMapper().writeValueAsString(ensureRequest); 
				
				//logger.info("reqBodyData ..=>"+ reqBodyData);
				
				// build the request
				//HttpEntity<JSONObject> requestEnty = new HttpEntity<>(ensureRequest, headers);
				HttpEntity<String> requestEnty = new HttpEntity<String>(ensureRequest.toString(), headers);
				
				logger.info("requestEnty ..=>"+ requestEnty);
				
				restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
				
				// send POST request
		        //ResponseEntity<String> response = restTemplate.postForEntity(baseUri+extApi, requestEnty, String.class);
				ResponseEntity<Object> response = restTemplate.exchange(baseUri+extApi,HttpMethod.POST, requestEnty, Object.class);
		        
		        logger.info("response ..=>"+ response);
		        logger.info("response getBody()..=>"+ response.getBody());
		        logger.info("response getStatusCode()..=>"+ response.getStatusCode());

				/*String respBody=response.getBody().toString();
				respBody=respBody.replace("{", "{\"").replace("=", "\":\"").replace(", ", "\",\"").replace("}", "\"}");
				respBody=respBody.replace(":\"{\"", ": {\"").replace("\"}\",", "\"},");
				logger.info("respBody JSONObj .. "+respBody);*/
		        
				
				// check response
		        if (response.getStatusCode() == HttpStatus.OK) {
		        	logger.info("Request Successful");
		        	
		        	String respBody=BankAuditUtil.convertStringToJSONObjectReadable(response.getBody().toString());
		            
		            org.json.simple.JSONObject jObj = (org.json.simple.JSONObject) JSONValue.parse(respBody);  
		            logger.info("jObj .. "+jObj);
		            String state = (String) jObj.get("state");
		            String msg = (String) jObj.get("msg");
		            String data = (String) jObj.get("data");
		            String userType = (String) jObj.get("userType");
		            
		            org.json.simple.JSONObject results=(org.json.simple.JSONObject)jObj.get("results");
		            String resStaus = (String) results.get("status");
		            String resMsg = (String) results.get("msg");
		            String resUserType = (String) results.get("userType");
		            
		            logger.info("state::"+state +" msg::"+msg+" userType::"+userType +" resStatus::"+resStaus+" resMsg::"+resMsg+" resUserType::"+resUserType);
		            logger.info("data=>PDF file path::"+data);
		            
		            String fileName=(data!=null?data.split("\\\\")[2].split("\\.")[0]:data);
		            logger.info("fileName .."+fileName);
		           
		            IfcEnsureBaasInterfaceDto ifcDto=new IfcEnsureBaasInterfaceDto();
		            ifcDto.setAuditId(auditId);
		            ifcDto.setAuditTypeCode(auditTypeCode);
		            ifcDto.setUnitId(unitCode);
		            ifcDto.setDocumentType(documentType);
		            ifcDto.setDocumentName(documentName);
		            ifcDto.setFileName(fileName);
		             
		            //logger.info(response.getBody());
		            //JSONParser parser=new JSONParser();
		            //org.json.simple.JSONObject jsonObject1=(org.json.simple.JSONObject) parser.parse(response.getBody().toString());
		            //logger.info("jsonObject1  .... => "+ jsonObject1);
		            
		            if("200".equals(resStaus)){
						serviceStatus.setResult(ifcDto);
						serviceStatus.setStatus("success");
						serviceStatus.setMessage("PDF Fetched Successfully ");
					}else {
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage(resStaus);
					}
		            
		        } else {
		        	logger.info("Request Failed");
		        	logger.info(response.getStatusCode());
		        }
				/***************************************** Rest Call, End here ***************************************/
				
				
				/**************** Only for SIT, Testing  *****************/
				/*IfcEnsureBaasInterfaceDto ifcDto=new IfcEnsureBaasInterfaceDto();
	            ifcDto.setAuditId(auditId);
	            ifcDto.setAuditTypeCode(auditTypeCode);
	            ifcDto.setUnitId(unitCode);
	            ifcDto.setDocumentType(documentType);
	            ifcDto.setDocumentName(documentName);
	            ifcDto.setFileName("TS_Inspection Report CSV_RRB_1_24022025183023.csv");
	            
	            serviceStatus.setResult(ifcDto);
				serviceStatus.setStatus("success");
				serviceStatus.setMessage("CSV Generated Successfully ");*/
				
				/*************** SIT Testing, to comment *******************/
			} catch (Exception e) {
				e.printStackTrace(System.out);
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
			return serviceStatus;
		}		
		
		
		
@RequestMapping(value="/fetchAuditLevelIRDocsTest" ,method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
		ServiceStatus  fetchAuditLevelIRDocsTest(
				@RequestParam(value="legalEntityCode")Integer legalEntityCode,
				@RequestParam(value="auditTypeCode")String auditTypeCode, 
				@RequestParam(value="auditId")String auditId, 
				@RequestParam(value="unitCode")String  unitCode)  {
			
			ServiceStatus serviceStatus=new ServiceStatus();
			 
			try {
				logger.info("Inside fetchAuditLevelIRCSVDocument .. "+ auditId+" .. "+auditTypeCode+" .. "+ unitCode);
				
				String extApi="api/SuperSoft/CrisMAc/InspectionCSV";
				String unitCodeP1=unitCode;  // License Code
				//String financialYearP3=myAuditsService.getFinancialYearByAuditId(legalEntityCode, auditTypeCode, auditId);
				String financialYearP3="2024-12-31";
				String auditTypeCodeP2=(auditTypeCode.contains("RRB")?"RRB":(auditTypeCode.contains("StCB")?"StCB":(auditTypeCode.contains("DCCB")?"DCCB":auditTypeCode)));
				
				HttpHeaders headers = new HttpHeaders();

				logger.info("Values ..=>"+ baseUri+extApi +" .. "+auditTypeCodeP2+" .. "+ unitCodeP1+" .. "+financialYearP3);
				
				//You can use more methods of HttpHeaders to set additional information
				// set `content-type` and other headers
				headers.setContentType(MediaType.APPLICATION_JSON);
				headers.set("APIKey",apiKey);
				headers.set("version",version);
				
				logger.info("headers ..=>"+ headers);
				
				// request body parameters
				JSONObject ensureRequest = new JSONObject();
				ensureRequest.put("licensee_Code", unitCodeP1);
				ensureRequest.put("licensee_Subtype", auditTypeCodeP2);
				ensureRequest.put("financial_Year", financialYearP3);
				ensureRequest.put("inspection_Frequency", 1);
				
				logger.info("ensureRequest ..=>"+ ensureRequest);
				
				// convert your request body to JSON formatted string using writeValueAsString() method of ObjectMapper 
				//String reqBodyData = new ObjectMapper().writeValueAsString(ensureRequest); 
				
				//logger.info("reqBodyData ..=>"+ reqBodyData);
				
				// build the request
				//HttpEntity<JSONObject> requestEnty = new HttpEntity<>(ensureRequest, headers);
				HttpEntity<String> requestEnty = new HttpEntity<String>(ensureRequest.toString(), headers);
				
				logger.info("requestEnty ..=>"+ requestEnty);
				
				restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
				
				// send POST request
		        //ResponseEntity<String> response = restTemplate.postForEntity(baseUri+extApi, requestEnty, String.class);
				ResponseEntity<Object> response = restTemplate.exchange(baseUri+extApi,HttpMethod.POST, requestEnty, Object.class);
		        
		        logger.info("response ..=>"+ response);
		        logger.info("response toSting()..=>"+ response.toString());
		        logger.info("response.getClass ..=>"+ response.getClass());
		        logger.info("response getBody()..=>"+ response.getBody());
		        logger.info("response getBody() to String..=>"+ response.getBody().toString());
		        logger.info("response getStatusCode()..=>"+ response.getStatusCode());

				/*String respBody=response.getBody().toString();
				respBody=respBody.replace("{", "{\"").replace("=", "\":\"").replace(", ", "\",\"").replace("}", "\"}");
				respBody=respBody.replace(":\"{\"", ": {\"").replace("\"}\",", "\"},");
				logger.info("respBody JSONObj .. "+respBody);*/
		        
				
				// check response
		        if (response.getStatusCode() == HttpStatus.OK) {
		        	logger.info("Request Successful");
		        	
		        	String respBody=BankAuditUtil.convertStringToJSONObjectReadable(response.getBody().toString());
		            
		            org.json.simple.JSONObject jObj = (org.json.simple.JSONObject) JSONValue.parse(respBody);  
		            logger.info("jObj .. "+jObj);
		            String state = (String) jObj.get("state");
		            String msg = (String) jObj.get("msg");
		            String data = (String) jObj.get("data");
		            String userType = (String) jObj.get("userType");
		            
		            org.json.simple.JSONObject results=(org.json.simple.JSONObject)jObj.get("results");
		            String resStaus = (String) jObj.get("status");
		            String resMsg = (String) jObj.get("msg");
		            String resUserType = (String) jObj.get("userType");
		           
		            IfcEnsureBaasInterfaceDto ifcDto=new IfcEnsureBaasInterfaceDto();
		            ifcDto.setFileName(data);
		             
		            //logger.info(response.getBody());
		            //JSONParser parser=new JSONParser();
		            //org.json.simple.JSONObject jsonObject1=(org.json.simple.JSONObject) parser.parse(response.getBody().toString());
		            //logger.info("jsonObject1  .... => "+ jsonObject1);
		            
		            serviceStatus.setStatus("Success");
					serviceStatus.setMessage(resMsg);
		            
		        } else {
		        	logger.info("Request Failed");
		        	logger.info(response.getStatusCode());
		        }
								
			} catch (Exception e) {
				logger.error(e.getStackTrace());
				e.printStackTrace(System.out);
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
			return serviceStatus;
		}		 
		
		/********************************************************************************************************
		 ********************************************************************************************************/
		
				// SIT TESTING Dummy method//
		
		
@RequestMapping(value="/fetchAuditLevelIRCSVDocument_SITTest" ,method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
		ServiceStatus  fetchAuditLevelCSVDocuments_SITTest(
				@RequestParam(value="maker")String maker, 
				@RequestParam(value="role")String role,
				@RequestParam(value="legalEntityCode")Integer legalEntityCode,
				@RequestParam(value="auditTypeCode")String auditTypeCode, 
				@RequestParam(value="auditId")String auditId, 
				@RequestParam(value="planId")String planId, 
				@RequestParam(value="documentType")String documentType,
				@RequestParam(value="warningCheck")String warningCheck, 
				@RequestParam(value="documentName")String  documentName,
				@RequestParam(value="unitCode")String  unitCode,
				@RequestParam(value="documentFetchType")String  docFetchType,
				@RequestParam(value="inspectionFrequency")String  inspectionFrequency,
				@RequestParam(value="seqId", required=false)String seqId)  {
			
			ServiceStatus serviceStatus=new ServiceStatus();
			 
			try {
				logger.info("Inside fetchAuditLevelIRCSVDocument .. "+ auditId+" .. "+auditTypeCode+" DocType ::"+documentType+" DocName ::"+documentName+" DoCFetchType ::"+docFetchType);
				String extApi=null;
				String unitCodeP1=unitCode;  // License Code
				String financialYearP3=myAuditsService.getFinancialYearByAuditId(legalEntityCode, auditTypeCode, auditId);
				String auditTypeCodeP2=(auditTypeCode.contains("RRB")?"RRB":(auditTypeCode.contains("StCB")?"StCB":(auditTypeCode.contains("DCCB")?"DCCB":auditTypeCode)));
				String fileName="";
				
				if("IRPartAB".equalsIgnoreCase(documentType)) {
					fileName="TS_Inspection Report CSV_RRB_1_24022025183023.csv";
				}else if("RatingCSV".equalsIgnoreCase(documentType)) {
					fileName="987_Rating CSV_RRB_1_26022025015636";
				}
				logger.info("fileName .."+ fileName);
				/**************** Only for SIT, Testing  *****************/
				IfcEnsureBaasInterfaceDto ifcDto=new IfcEnsureBaasInterfaceDto();
	            ifcDto.setAuditId(auditId);
	            ifcDto.setAuditTypeCode(auditTypeCode);
	            ifcDto.setUnitId(unitCode);
	            ifcDto.setDocumentType(documentType);
	            ifcDto.setDocumentName(documentName);
	            ifcDto.setFileName(fileName);
	            
	            serviceStatus.setResult(ifcDto);
				serviceStatus.setStatus("success");
				serviceStatus.setMessage("CSV Generated Successfully ");
				
				/*************** SIT Testing, to comment *******************/
			} catch (Exception e) {
				e.printStackTrace(System.out);
				if (e instanceof InternalServerErrorException) {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("The ENSURE server is not reachable.");
		        }
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
			return serviceStatus;
		}		 
		
				
		
		
@RequestMapping(value="/fetchAuditLevelAppendix_SITTest" ,method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
		ServiceStatus  fetchAuditLevelAppendix_SITTest(
				@RequestParam(value="maker")String maker, 
				@RequestParam(value="role")String role,
				@RequestParam(value="legalEntityCode")Integer legalEntityCode,
				@RequestParam(value="auditTypeCode")String auditTypeCode, 
				@RequestParam(value="auditId")String auditId, 
				@RequestParam(value="planId")String planId, 
				@RequestParam(value="documentType")String documentType,
				@RequestParam(value="warningCheck")String warningCheck, 
				@RequestParam(value="documentName")String  documentName,
				@RequestParam(value="unitCode")String  unitCode,
				@RequestParam(value="documentFetchType")String  docFetchType,
				@RequestParam(value="inspectionFrequency")String  inspectionFrequency,
				@RequestParam(value="seqId", required=false)String  seqId)  {
			
			ServiceStatus serviceStatus=new ServiceStatus();
			 
			try {
				logger.info("Inside fetchAuditLevelAppendix .. "+ auditId+" .. "+auditTypeCode+" DocType ::"+documentType+" DocName ::"+documentName+" DocFetchType ::"+docFetchType);
				String extApi="api/SuperSoft/CrisMAc/AppendixPDF";
				String unitCodeP1=unitCode;  // License Code
				String financialYearP3=myAuditsService.getFinancialYearByAuditId(legalEntityCode, auditTypeCode, auditId);
				String auditTypeCodeP2=(auditTypeCode.contains("RRB")?"RRB":(auditTypeCode.contains("StCB")?"StCB":(auditTypeCode.contains("DCCB")?"DCCB":auditTypeCode)));
				//String nameOfPdfFileP5=(docFetchType.equalsIgnoreCase("IRPartC_Apx_IV")?"APPENDIX_I_TO_IV":
					//	(docFetchType.equalsIgnoreCase("IRPartC_Apx_VII")?"APPENDIX_VII":(docFetchType.equalsIgnoreCase("IRPartC_Apx_VIII")?"APPENDIX_VIII":docFetchType)));
				
				logger.info("auditTypeCodeP2 "+ auditTypeCodeP2+":: "+financialYearP3);
				String fileName="";
				IfcEnsureBaasInterfaceDto ifcDto=new IfcEnsureBaasInterfaceDto();
	            ifcDto.setAuditId(auditId);
	            ifcDto.setAuditTypeCode(auditTypeCode);
	            ifcDto.setUnitId(unitCode);
	            ifcDto.setDocumentType(documentType);
	            ifcDto.setDocumentName(documentName);
	           				
				
				if("IRPartC_Apx_IV".equalsIgnoreCase(docFetchType)) {  // RRBEI, DCCBEI, StCBEI
					fileName="TS_APPENDIX_I_TO_IV_RRB_27022025123831";
				}else if("IRPartC_Apx_VII".equalsIgnoreCase(docFetchType)) {  // DCCBI, StCBI
					fileName="TS_IRPartC_APPENDIX_VII.pdf";
				}else if("IRPartC_Apx_VIII".equalsIgnoreCase(docFetchType)) {  
					fileName="TS_IRPartC_APPENDIX_VIII.pdf";
				}else if("RN".equalsIgnoreCase(documentType)) {  
					fileName="TS_IRPartC_APPENDIX_VIII.pdf";
				}else if("LoSC".equalsIgnoreCase(documentType)) {  
					fileName="TS_APPENDIX_I_TO_IV_RRB_27022025123831";
				}
				
				ifcDto.setFileName(fileName);
		            
				serviceStatus.setResult(ifcDto);
				serviceStatus.setStatus("success");
				serviceStatus.setMessage("CSV Generated Successfully ");
				
				/*************** SIT Testing, to comment *******************/
			} catch (Exception e) {
				e.printStackTrace(System.out);
				if (e instanceof InternalServerErrorException) {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("The ENSURE server is not reachable.");
		        }
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
				
			}
			return serviceStatus;
		}
		
		// SIT TESTING Dummy method, End here //
		
}
