package com.bankaudit.rest.process.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
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.multipart.commons.CommonsMultipartFile;

import com.bankaudit.constants.BankAuditConstant;
import com.bankaudit.dto.DataTableResponse;
import com.bankaudit.dto.process.AuditLevelDocumentDetailsDto;
import com.bankaudit.process.model.AuditLevelDocumentDetails;
import com.bankaudit.rest.process.service.AuditRatingParameterScoreService;
import com.bankaudit.rest.process.service.IfcDataOfflineUploadService;
import com.bankaudit.rest.process.service.IfcEnsureBaasDataService;
import com.bankaudit.service.UserService;
import com.bankaudit.spring.config.BankAuditConfig;
import com.bankaudit.util.BankAuditUtil;
import com.bankaudit.util.ServiceStatus;




@RestController

@RequestMapping("/api/ifcEnsureBaasData")
public class IfcEnsureBaasDataController {
	 
	@Autowired
	IfcEnsureBaasDataService  ifcEnsureBaasDataService;
	
	@Autowired
	IfcDataOfflineUploadService  ifcEnsureBaasDataOfflineUploadService;
	
	@Autowired
	AuditRatingParameterScoreService  auditRatingParameterScoreService;	
	
	@Autowired
	UserService userService;	
		
	static final Logger logger = Logger.getLogger(IfcEnsureBaasDataController.class);	
	
	private String functionId="ifcEnsureBaasData";
	
		
@RequestMapping(value="/uploadIndividualAuditLevelCSVDocument" ,method=RequestMethod.POST,consumes=MediaType.MULTIPART_FORM_DATA_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)
		ServiceStatus  uploadIndividualAuditLevelCSVDocument(
				@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="documentName")String  documentName,
				@RequestParam(value="documentSubType")String documentSubType,
				@RequestParam(value="warningCheck")String warningCheck, 
				@RequestParam(value="unitCode")String  unitCode,
				@RequestParam(value="seqId")String  seqId,
				@RequestParam(value="documentFetchType" ,required=false)String  documentFetchType,
				@RequestParam(value="uploadOrFetch" ,required=false)String  uploadOrFetch)  {
			
			ServiceStatus serviceStatus=new ServiceStatus();
			 
			try {
				if(files!=null){					
									 			   			
					String fileName=legalEntityCode.toString()+auditTypeCode+auditId+role+documentType;
					 

					List<String> filesNamesList = new ArrayList<>(); 
					List<String>  filesNamesListDuplicate = new ArrayList<>(); 
					
					/*for (CommonsMultipartFile commonsMultipartFile : files) {						
						if(!BankAuditUtil.validateFileType(commonsMultipartFile, BankAuditConstant.DOC_TYPES)){
							serviceStatus.setStatus("failure");
							serviceStatus.setMessage("file type : "+BankAuditUtil.getFileExtension(commonsMultipartFile.getOriginalFilename()) +" not supported");
							return serviceStatus;
						}						
						//filesNamesList.add(commonsMultipartFile.getOriginalFilename());
					} */
					 
					filesNamesListDuplicate  = 
							ifcEnsureBaasDataService.checkDuplicateAuditLevelDocuments(legalEntityCode, auditTypeCode, auditId, planId, documentType, 
									documentSubType, documentFetchType, filesNamesList);
					
					if(warningCheck.equalsIgnoreCase("yes")) {							 						
						if(filesNamesListDuplicate!=null && !filesNamesListDuplicate.isEmpty() && filesNamesListDuplicate.size()>0){
							serviceStatus.setStatus("warning");
							serviceStatus.setMessage("csv file already exist do you want to replace  ");
							serviceStatus.setResult(filesNamesListDuplicate );
							return serviceStatus;
						} 
					}	
					
					String statusMessage = BankAuditConstant.SUCCESS;
					if(warningCheck.equalsIgnoreCase("no") && !filesNamesListDuplicate.isEmpty() && filesNamesListDuplicate.size()>0 )
					  statusMessage = ifcEnsureBaasDataService.deleteDuplicateDocument(legalEntityCode, auditTypeCode, auditId, planId, 
							documentType, documentSubType, documentFetchType, filesNamesListDuplicate);
					
					//result.put("documentUploadId", auditObservationService.uploadDocument(maker,role,files,fileName));
					if(statusMessage.equalsIgnoreCase(BankAuditConstant.SUCCESS)){
						AuditLevelDocumentDetails auditDocumentDetails =  new AuditLevelDocumentDetails();
						auditDocumentDetails.setLegalEntityCode(legalEntityCode);
						auditDocumentDetails.setAuditTypeCode(auditTypeCode); 
						auditDocumentDetails.setAuditId(auditId);
						auditDocumentDetails.setPlanId(planId);
						auditDocumentDetails.setDocumentType(documentType); 
						auditDocumentDetails.setDocumentSubType(documentSubType); 
						auditDocumentDetails.setDocumentName(documentName);	
						auditDocumentDetails.setDocumentFetchType(documentFetchType);
						//auditDocumentDetails.setDocumentSubType("");  
						auditDocumentDetails.setMaker(maker);  			 
						auditDocumentDetails.setMakerTimestamp(new Timestamp(System.currentTimeMillis()));
						auditDocumentDetails.setUserRoleId(role);					
						auditDocumentDetails.setUnitCode(unitCode);
						auditDocumentDetails.setSeqId(seqId);
						auditDocumentDetails.setDocumentFetchType(documentFetchType);
						auditDocumentDetails.setUploadOrFetch(uploadOrFetch);
						auditDocumentDetails.setUploadStatus(BankAuditConstant.STATUS_INACTIVE);
						
						 statusMessage =  ifcEnsureBaasDataService.uploadIndividualAuditLevelCSVDocument(auditDocumentDetails, files, fileName);
						
						if(statusMessage.equalsIgnoreCase(BankAuditConstant.SUCCESS)){
							serviceStatus.setResult("success");
							serviceStatus.setStatus("success");
							serviceStatus.setMessage("successfully uploaded");
						}else{
							serviceStatus.setStatus("failure");
							serviceStatus.setMessage("failure");
						}
					}else{
						serviceStatus.setResult(statusMessage);
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("failure");
					}
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("Invalid payload");
				}
				
			} catch (Exception e) {
				logger.error(e.getStackTrace());
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
			return serviceStatus;
		}
				
		
@RequestMapping(value="/uploadIndividualAuditLevelPdfDocument" ,method=RequestMethod.POST,consumes=MediaType.MULTIPART_FORM_DATA_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)
		ServiceStatus  uploadIndividualAuditLevelPdfDocument(
				@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="documentSubType")String documentSubType,
				@RequestParam(value="warningCheck")String warningCheck, 
				@RequestParam(value="documentName")String  documentName,
				@RequestParam(value="unitCode")String  unitCode,
				@RequestParam(value="seqId")String  seqId,
				@RequestParam(value="documentFetchType" ,required=false)String  documentFetchType,
				@RequestParam(value="uploadOrFetch" ,required=false)String  uploadOrFetch)  {
			
			ServiceStatus serviceStatus=new ServiceStatus();
			 
			try {
				if(files!=null){
					 		
					String fileName=legalEntityCode.toString()+auditTypeCode+auditId+role+documentType;
					List<String> filesNamesList = new ArrayList<>(); 
					List<String>  filesNamesListDuplicate = new ArrayList<>(); 
					
					for (CommonsMultipartFile commonsMultipartFile : files) {
						 
						
						if(!BankAuditUtil.validateFileType(commonsMultipartFile, BankAuditConstant.DOC_TYPES)){
							serviceStatus.setStatus("failure");
							serviceStatus.setMessage("file type : "+BankAuditUtil.getFileExtension(commonsMultipartFile.getOriginalFilename()) +" not supported");
							return serviceStatus;
						}
						
						filesNamesList.add(commonsMultipartFile.getOriginalFilename());
					} 
					 
					filesNamesListDuplicate  = 
							ifcEnsureBaasDataService.checkDuplicateAuditLevelDocuments(legalEntityCode, auditTypeCode, auditId, planId, documentType,
									documentSubType, documentFetchType, filesNamesList);
					
					if(warningCheck.equalsIgnoreCase("yes")) {							 						
						if(filesNamesListDuplicate!=null && !filesNamesListDuplicate.isEmpty() && filesNamesListDuplicate.size()>0){
							serviceStatus.setStatus("warning");
							serviceStatus.setMessage("file " + filesNamesListDuplicate + "  already exist do you want to replace  ");
							serviceStatus.setResult(filesNamesListDuplicate );
							return serviceStatus;
						} 
					}							
					 						
					//result.put("documentUploadId", auditObservationService.uploadDocument(maker,role,files,fileName));
					/**** Delete if same file exist ****/	
					String statusMessage = BankAuditConstant.SUCCESS;
					if(warningCheck.equalsIgnoreCase("no") && !filesNamesListDuplicate.isEmpty() && filesNamesListDuplicate.size()>0 )
					  statusMessage = ifcEnsureBaasDataService.deleteDuplicateDocument(legalEntityCode, auditTypeCode, auditId, planId, 
							documentType, documentSubType, documentFetchType, filesNamesListDuplicate);
					
					if(statusMessage.equalsIgnoreCase(BankAuditConstant.SUCCESS)){
						AuditLevelDocumentDetails auditDocumentDetails =  new AuditLevelDocumentDetails();
						auditDocumentDetails.setLegalEntityCode(legalEntityCode);
						auditDocumentDetails.setAuditTypeCode(auditTypeCode); 
						auditDocumentDetails.setAuditId(auditId);
						auditDocumentDetails.setPlanId(planId);
						auditDocumentDetails.setDocumentType(documentType);  
						auditDocumentDetails.setDocumentSubType(documentSubType);  
						auditDocumentDetails.setMaker(maker);  			 
						auditDocumentDetails.setMakerTimestamp(new Timestamp(System.currentTimeMillis()));
						auditDocumentDetails.setUserRoleId(role);					
						auditDocumentDetails.setUnitCode(unitCode);
						auditDocumentDetails.setDocumentName(documentName);	 
						auditDocumentDetails.setSeqId(seqId);
						auditDocumentDetails.setDocumentFetchType(documentFetchType);
						auditDocumentDetails.setUploadOrFetch(uploadOrFetch);
						auditDocumentDetails.setUploadStatus(BankAuditConstant.STATUS_INACTIVE);				  
						
						String documentUploadId =  ifcEnsureBaasDataService.uploadIndividualAuditLevelPdfDocument(auditDocumentDetails, files, fileName);
						serviceStatus.setResult(documentUploadId);
						if(documentUploadId.equalsIgnoreCase(BankAuditConstant.SUCCESS)){						
							serviceStatus.setStatus("success");
							serviceStatus.setMessage("successfully uploaded");
						}else{
							serviceStatus.setStatus("failure");
							serviceStatus.setMessage("failure");
						}
					}
					else{
						serviceStatus.setResult(statusMessage);
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("failure");
					}
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("Invalid payload");
				}
				
			} catch (Exception e) {
				logger.error(e.getStackTrace());
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
			return serviceStatus;
		}	 
		
		
@RequestMapping(value="/saveFetchedIndividualAuditLevelCSVDocument" ,method=RequestMethod.POST,consumes=MediaType.APPLICATION_JSON_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)
		ServiceStatus  saveFetchedIndividualAuditLevelCSVDocument(@RequestBody AuditLevelDocumentDetails auditLevelDocumentDetails)  {			
			ServiceStatus serviceStatus=new ServiceStatus();			 
			try {
				String status =BankAuditConstant.SUCCESS;
				if(auditLevelDocumentDetails !=null && !BankAuditUtil.isEmptyString(auditLevelDocumentDetails.getFileName())
						&& !BankAuditUtil.isEmptyString(auditLevelDocumentDetails.getDocumentType())){ 					 
					
					List<String> filesNamesListDuplicate  = 
							ifcEnsureBaasDataService.checkDuplicateAuditLevelDocuments(auditLevelDocumentDetails.getLegalEntityCode(), auditLevelDocumentDetails.getAuditTypeCode(),
									auditLevelDocumentDetails.getAuditId(), auditLevelDocumentDetails.getPlanId(), auditLevelDocumentDetails.getDocumentType(), 
									auditLevelDocumentDetails.getDocumentSubType(), auditLevelDocumentDetails.getDocumentFetchType(), null);					
					if(filesNamesListDuplicate!=null && !filesNamesListDuplicate.isEmpty()) {
						status = ifcEnsureBaasDataService.deleteDuplicateDocument(auditLevelDocumentDetails.getLegalEntityCode(), auditLevelDocumentDetails.getAuditTypeCode(), 
							auditLevelDocumentDetails.getAuditId(), auditLevelDocumentDetails.getPlanId(), 	auditLevelDocumentDetails.getDocumentType(), 
							auditLevelDocumentDetails.getDocumentSubType(), auditLevelDocumentDetails.getDocumentFetchType(), filesNamesListDuplicate);
					}
					if(status.equalsIgnoreCase(BankAuditConstant.SUCCESS)){	
						status =  ifcEnsureBaasDataService.saveFetchedIndividualAuditLevelCSVDocument(auditLevelDocumentDetails);
						if(status.equalsIgnoreCase(BankAuditConstant.SUCCESS)){						
							serviceStatus.setStatus("success");
							serviceStatus.setMessage("successfully uploaded");
						}else{
							serviceStatus.setStatus("failure");
							serviceStatus.setMessage("failure");
						}
					}else{
						serviceStatus.setResult(status);
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("failure");
					}
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("Invalid payload");
				}
				
			} catch (Exception e) {
				logger.error(e.getStackTrace());
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
			return serviceStatus;
		}
		
		
@RequestMapping(value="/saveFetchedIndividualAuditLevelPdfDocument" ,method=RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces=MediaType.APPLICATION_JSON_VALUE)
		ServiceStatus  saveFetchedIndividualAuditLevelPdfDocument(@RequestBody AuditLevelDocumentDetails auditLevelDocumentDetails)  {			
			ServiceStatus serviceStatus=new ServiceStatus(); 
			try {
				if(auditLevelDocumentDetails !=null && !BankAuditUtil.isEmptyString(auditLevelDocumentDetails.getFileName())
						&& !BankAuditUtil.isEmptyString(auditLevelDocumentDetails.getDocumentType())){ 					
					String status =  ifcEnsureBaasDataService.saveFetchedIndividualAuditLevelPdfDocument(auditLevelDocumentDetails);
					serviceStatus.setResult(status);
					if(status.equalsIgnoreCase(BankAuditConstant.SUCCESS)){						
						serviceStatus.setStatus("success");
						serviceStatus.setMessage("successfully uploaded");
					}else{
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("failure");
					}					 
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("Invalid payload");
				}				
			} catch (Exception e) {
				logger.error(e.getStackTrace());
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
			return serviceStatus;
		}	
		
		
@RequestMapping(value="/uploadOfflineInspection" ,method=RequestMethod.POST,consumes=MediaType.MULTIPART_FORM_DATA_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)
		ServiceStatus  uploadOfflineInspection(
				@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,
				@RequestParam(value="reportLanguage")String  reportLanguage)  {
			
			ServiceStatus serviceStatus=new ServiceStatus();
			 
			try {
				if(files!=null){					
									 			   			
					String fileName=legalEntityCode.toString()+auditTypeCode+auditId+role+documentType;				   
					AuditLevelDocumentDetails auditDocumentDetails =  new AuditLevelDocumentDetails();
					auditDocumentDetails.setLegalEntityCode(legalEntityCode);
					auditDocumentDetails.setAuditTypeCode(auditTypeCode); 
					auditDocumentDetails.setAuditId(auditId);
					auditDocumentDetails.setPlanId(planId);
					auditDocumentDetails.setDocumentType(documentType); 
					auditDocumentDetails.setDocumentName(documentName);					
					auditDocumentDetails.setDocumentSubType("");  
					auditDocumentDetails.setMaker(maker);  			 
					auditDocumentDetails.setMakerTimestamp(new Timestamp(System.currentTimeMillis()));
					auditDocumentDetails.setUserRoleId(role);					
					auditDocumentDetails.setUnitCode(unitCode);
					auditDocumentDetails.setSeqId(seqId);
					auditDocumentDetails.setUploadStatus(BankAuditConstant.STATUS_INACTIVE);
					
					//String statusMessage =  ifcEnsureBaasDataService.uploadOfflineInspection(auditDocumentDetails, files, fileName, reportLanguage);
					String statusMessage =  ifcEnsureBaasDataOfflineUploadService.uploadOfflineInspection(auditDocumentDetails, files, fileName, reportLanguage);
					
					if(statusMessage.equalsIgnoreCase(BankAuditConstant.SUCCESS)){						
						serviceStatus.setStatus("success");
						serviceStatus.setMessage("successfully uploaded");
					}else if(statusMessage.equalsIgnoreCase(BankAuditConstant.VALIDATION_FAILED)){
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("Validation failed, please check Inspection Id and Inspection Type");
					}else{
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("failed to upload excel");
					}
					 
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("Invalid payload");
				}
				
			} catch (Exception e) {
				logger.error(e.getStackTrace());
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
			return serviceStatus;
		}
		
		
@RequestMapping(value="/getAuditLevelDocuments" ,method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
		ServiceStatus  getAuditLevelDocuments(	 
			@RequestParam("legalEntityCode")Integer legalEntityCode,
			@RequestParam("auditId")String auditId, 
			@RequestParam("planId")String planId, 
			@RequestParam("auditTypeCode")String auditTypeCode, 			
			@RequestParam(value="documentType", required=false)String documentType,
			@RequestParam(value="userId", required=false)String loginUserId,
			@RequestParam("role")String role)  {
			
				ServiceStatus serviceStatus=new ServiceStatus();
			
				try {
					logger.info("getAuditLevelDocuments legalEntityCode:: "+legalEntityCode +" loginUserId:: "+ loginUserId+" role:: "+role);
					boolean validUsrforRole=userService.isUserHavingEntitlement(legalEntityCode, loginUserId, role, functionId, "getAuditLevelDocuments");
					
					if(validUsrforRole) {					
						List<AuditLevelDocumentDetails> auditLevelDocumentDetails=ifcEnsureBaasDataService.getAuditLevelDocuments(legalEntityCode, auditTypeCode, auditId, planId, documentType, role);
						
						if(auditLevelDocumentDetails!=null && !auditLevelDocumentDetails.isEmpty()){
							serviceStatus.setResult(auditLevelDocumentDetails);
							serviceStatus.setStatus("success");
							serviceStatus.setMessage("File successfully retrieved ");
							
						}else {
							serviceStatus.setStatus("success");
							serviceStatus.setMessage("No docs found ");
						}
					}else {
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("failure");
					}					
					
				} catch (Exception e) {
					logger.error(e.getStackTrace());
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("failure");
				}
			return serviceStatus;
		} 
		

		
@RequestMapping(value="/deletePdfDocument" ,method=RequestMethod.DELETE,produces=MediaType.APPLICATION_JSON_VALUE)
		ServiceStatus  deletePdfDocument(	 
			@RequestParam("legalEntityCode")Integer legalEntityCode,
			@RequestParam("auditId")String auditId, 
			@RequestParam("planId")String planId, 
			@RequestParam("auditTypeCode")String auditTypeCode, 			
			@RequestParam(value="documentType")String documentType,
			@RequestParam("id")Integer id)  {
			
				ServiceStatus serviceStatus=new ServiceStatus();
			
				try {
					
					String statusMessage =ifcEnsureBaasDataService.deletePdfDocument(legalEntityCode, auditTypeCode, auditId, planId, documentType, id);
					
					serviceStatus.setResult(statusMessage);
					if(statusMessage.equalsIgnoreCase(BankAuditConstant.SUCCESS)){							
						serviceStatus.setStatus("success");
						serviceStatus.setMessage("successfully got the result ");					
					}else {
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("failure");
					}
					
				} catch (Exception e) {
					logger.error(e.getStackTrace());
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("failure");
				}
			return serviceStatus;
		} 
		
		
@RequestMapping(value="/downloadDocument",method = RequestMethod.GET)
	    public void  downloadDocument(
	    		@RequestParam(value="id",required=true)Integer id,
	    		@RequestParam(value="legalEntityCode",required=true)Integer legalEntityCode,  
	    		@RequestParam(value="documentType",required=true)String documentType, 
	    		@RequestParam(value="auditTypeCode")String auditTypeCode, 
				@RequestParam(value="auditId")String auditId,	    		
	    		HttpServletRequest request,
	            HttpServletResponse response) throws IOException {    	
	    	
	    	ServletContext context=request.getServletContext();
	    	String filePath =ifcEnsureBaasDataService.getDocReferencePath(legalEntityCode, auditTypeCode, auditId, documentType, id);
	    	logger.info("downloadDocument => filePath :: "+ filePath);
	    	 	if(!BankAuditUtil.isEmptyString(filePath)){
			    		File file=new File(filePath);
			    		if(file.isFile()){
			    			
			    			 int BUFFER_SIZE = 4096;
			    			 FileInputStream inputStream = new FileInputStream(file);

			    			 String mimeType = context.getMimeType(filePath); // get MIME type of the file
			                 
			                 if (mimeType == null) {
			                     mimeType = "application/octet-stream"; // set to binary type if MIME mapping not found
			                 }
			              
			                 // set content attributes for the response
			                 response.setContentType(mimeType);
			                 response.setContentLength((int) file.length());
			          
			                 // set headers for the response
			                 String headerKey = "Content-Disposition";
			                 String headerValue = String.format("attachment; filename=\"%s\"",file.getName());
			                 response.setHeader(headerKey, headerValue);
			          
			                 // get output stream of the response
			                 OutputStream outStream = response.getOutputStream();
			          
			                 byte[] buffer = new byte[BUFFER_SIZE];
			                 int bytesRead = -1;
			          
			                 // write bytes read from the input stream into the output stream
			                 while ((bytesRead = inputStream.read(buffer)) != -1) {
			                     outStream.write(buffer, 0, bytesRead);
			                 }
			                 inputStream.close();
			                 outStream.close();                  
			        	}else {
			    			 response.getWriter().print("Document not exist");
						}
			    }else {
	   			 response.getWriter().print("Document not exist");
				}
	   	}
		
		
@RequestMapping(value="/downloadDocumentEnsure",method = RequestMethod.GET)
	    public void downloadDocumentEnsure( 
	    		@RequestParam(value="legalEntityCode",required=true)Integer legalEntityCode,  
	    		@RequestParam(value="fileName",required=true)String fileName, 
	    		//@RequestParam(value="path")String path,  	    		
	    		HttpServletRequest request,
	            HttpServletResponse response) throws IOException {    	
	    	
	    	ServletContext context=request.getServletContext();
	    	logger.info("Inside downloadDocumentEnsure .. "+ legalEntityCode +" :: "+ fileName);
	    	String filePath = BankAuditConfig.getInstance().getConfigValue(BankAuditConstant.DIR_DOC_ENSURE_INTERFACE)+"/"+fileName; 
	    	logger.info("downloadDocumentEnsure =>filePath .. "+ filePath);
	    	 	if(!BankAuditUtil.isEmptyString(filePath)){
			    		File file=new File(filePath);
			    		logger.info("file .. "+ filePath);
			    		if(file.isFile()){
			    			logger.info("isFile Yes .. ");
			    			 int BUFFER_SIZE = 4096;
			    			 FileInputStream inputStream = new FileInputStream(file);

			    			 String mimeType = context.getMimeType(filePath); // get MIME type of the file			                 
			                 if (mimeType == null) {
			                     mimeType = "application/octet-stream"; // set to binary type if MIME mapping not found
			                 }			              
			                 // set content attributes for the response
			                 response.setContentType(mimeType);
			                 response.setContentLength((int) file.length());
			                 
			                 // set headers for the response
			                 String headerKey = "Content-Disposition";
			                 String headerValue = String.format("attachment; filename=\"%s\"",file.getName());
			                 response.setHeader(headerKey, headerValue);
			          
			                 // get output stream of the response
			                 OutputStream outStream = response.getOutputStream();
			          
			                 byte[] buffer = new byte[BUFFER_SIZE];
			                 int bytesRead = -1;
			          
			                 // write bytes read from the input stream into the output stream
			                 while ((bytesRead = inputStream.read(buffer)) != -1) {
			                     outStream.write(buffer, 0, bytesRead);
			                 }
			                 inputStream.close();
			                 outStream.close();                  
			        	}else {
			        		logger.info("is not a File");
			    			 response.getWriter().print("Document not exist");
						}
			    }else {
	   			 response.getWriter().print("Document not exist");
				}
	   	}
		
		
@RequestMapping(value="/updatePdfDocumentSequence" ,method=RequestMethod.PUT,consumes=MediaType.APPLICATION_JSON_VALUE, produces=MediaType.APPLICATION_JSON_VALUE)
		//ServiceStatus  updatePdfDocumentSequence(@RequestBody List<AuditLevelDocumentDetails> listAuditLevelDocumentDetails)  {
		ServiceStatus  updatePdfDocumentSequence(@RequestBody AuditLevelDocumentDetailsDto auditLevelDocumentDetails)  {
		
				ServiceStatus serviceStatus=new ServiceStatus();
			
				try {
					
					String statusMessage =ifcEnsureBaasDataService.updatePdfDocumentSequence(auditLevelDocumentDetails.getAuditLevelDocumentDetails());
					
					serviceStatus.setResult(statusMessage);
					if(statusMessage.equalsIgnoreCase(BankAuditConstant.SUCCESS)){							
						serviceStatus.setStatus("success");
						serviceStatus.setMessage("successfully updated the sequence ");					
					}else {
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("failure");
					}
					
				} catch (Exception e) {
					logger.error(e.getStackTrace());
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("failure");
				}
			return serviceStatus;
		} 
		
		
@RequestMapping(value="/viewOfflineInspectionData" ,method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
		DataTableResponse  viewOfflineInspection(					
				@RequestParam("draw") String drawStr,
				@RequestParam("length") String length,
				@RequestParam("start") String start,
				@RequestParam("search[value]") String search,
				@RequestParam("order[0][column]") String orderColumnStr,
				@RequestParam("order[0][dir]") String orderDirection,
				@RequestParam("id")Integer id,
				@RequestParam("legalEntityCode")Integer legalEntityCode,
				@RequestParam("auditId")String auditId, 
				@RequestParam("auditTypeCode")String auditTypeCode 
				)  {
			
			DataTableResponse listIfcEnsureBaasData = null;
			if (!BankAuditUtil.isEmptyString(drawStr) && !BankAuditUtil.isEmptyString(length)
					&& !BankAuditUtil.isEmptyString(start)) {
				try {
					Integer draw = Integer.parseInt(drawStr);
					Integer size = Integer.parseInt(length);
					Integer page = Integer.parseInt(start) / size;
					Integer orderColumn = null;
					if (!BankAuditUtil.isEmptyString(orderColumnStr)) {
						orderColumn = Integer.parseInt(orderColumnStr);
					} 		
					listIfcEnsureBaasData =	ifcEnsureBaasDataService.viewOfflineInspection(id, legalEntityCode, auditTypeCode, auditId, search, orderColumn, orderDirection, page, size);
			  
				} catch (Exception e) {
					listIfcEnsureBaasData = new DataTableResponse();
					listIfcEnsureBaasData.setError(e.getMessage());
					logger.error(e.getStackTrace());
				}
			} else {
				listIfcEnsureBaasData = new DataTableResponse();
				listIfcEnsureBaasData.setError("invalid data");
			}
			
			return listIfcEnsureBaasData;
		}
		
		
@RequestMapping(value = "/downloadOfflineUploadedInspection", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
		void downloadOfflineUploadedInspection( 
				@RequestParam("id")Integer id,
				@RequestParam("legalEntityCode")Integer legalEntityCode,
				@RequestParam("auditId")String auditId, 
				@RequestParam("auditTypeCode")String auditTypeCode ,
				@RequestParam("role")String role ,
				HttpServletRequest request,      HttpServletResponse response){

			if(legalEntityCode!=null && legalEntityCode>0 && (auditId!=null && !BankAuditUtil.isEmptyString(auditId)) ){ 
				try { 	 
					
					ByteArrayOutputStream byteData = ifcEnsureBaasDataService.downloadOfflineInspection(id, legalEntityCode, auditTypeCode, auditId, role);
						
					if(byteData!=null){ 	
						 String fileName = "UploadedCheckList_"+auditId+"_"+legalEntityCode+".xlsx"; 	 					
						 String mimeType ="application/vnd.ms-excel";  						 
			             response.setContentType(mimeType); 
			             String headerKey = "Content-Disposition";
			             String headerValue = String.format("attachment; filename=\"%s\"", fileName);
			             response.setHeader(headerKey, headerValue); 
			             OutputStream outStream = response.getOutputStream();
			             outStream.write(byteData.toByteArray());		    
			             outStream.close();               
			    	}else {
						 response.getWriter().print("Document not exist");
					}			     
				} catch (Exception e) {
					e.printStackTrace();					
				}
			}			
		} 
		
		
@RequestMapping(value="/uploadRatingParameterScoresByAuditId" ,method=RequestMethod.POST,consumes=MediaType.MULTIPART_FORM_DATA_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)
		ServiceStatus  uploadRatingParameterScoresByAuditId(
				@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="userType")String userType)  {
			
			ServiceStatus serviceStatus=new ServiceStatus();
			 
			try {
				if(files!=null){					
									 			   			
					String fileName=legalEntityCode.toString()+auditTypeCode+auditId+role+documentType;				   
					AuditLevelDocumentDetails auditLevelDocumentDetails =  new AuditLevelDocumentDetails();
					auditLevelDocumentDetails.setLegalEntityCode(legalEntityCode);
					auditLevelDocumentDetails.setAuditTypeCode(auditTypeCode); 
					auditLevelDocumentDetails.setAuditId(auditId);
					auditLevelDocumentDetails.setPlanId(planId);
					auditLevelDocumentDetails.setDocumentType(documentType); 
					auditLevelDocumentDetails.setDocumentName(documentName);					
					auditLevelDocumentDetails.setDocumentSubType("");  
					auditLevelDocumentDetails.setMaker(maker);  			 
					auditLevelDocumentDetails.setMakerTimestamp(new Timestamp(System.currentTimeMillis()));
					auditLevelDocumentDetails.setUserRoleId(role);					
					auditLevelDocumentDetails.setUnitCode(unitCode);
					auditLevelDocumentDetails.setSeqId("");
					auditLevelDocumentDetails.setUploadStatus(BankAuditConstant.STATUS_INACTIVE);
					 
					String statusMessage =  ifcEnsureBaasDataOfflineUploadService.uploadRatingParameterScoresByAuditId(auditLevelDocumentDetails, 
							files, fileName, userType, maker);
					
					if(statusMessage.equalsIgnoreCase(BankAuditConstant.SUCCESS)){
						 boolean status= auditRatingParameterScoreService.executeAnUpdateWeightedScore(legalEntityCode, auditId, userType); // Service call to update the Weighted Score
						 statusMessage=(status?"S":"Failure");
					}
					if(statusMessage.equalsIgnoreCase(BankAuditConstant.SUCCESS)){						
						serviceStatus.setStatus("success");
						serviceStatus.setMessage("successfully uploaded");
					}else if(statusMessage.equalsIgnoreCase(BankAuditConstant.VALIDATION_FAILED)){
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("Validation failed, please check Inspection Id and Inspection Type");
					}else if(statusMessage.equalsIgnoreCase("Failure")){
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("Weightage update failure during Error of Approximation ");
					}else{
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("failed to upload excel");
					}
					 
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("Invalid payload");
				}
				
			} catch (Exception e) {
				logger.error(e.getStackTrace());
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
			return serviceStatus;
		}
		
		
@RequestMapping(value="/uploadAuditRatingComplianceObsScore" ,method=RequestMethod.POST,consumes=MediaType.MULTIPART_FORM_DATA_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)
		ServiceStatus  uploadAuditRatingComplianceObsScore(
				@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="ratingComplianceStatus")String ratingComplianceStatus)  {
			
			ServiceStatus serviceStatus=new ServiceStatus();
			 
			try {
				if(files!=null){					
									 			   			
					String fileName=legalEntityCode.toString()+auditTypeCode+auditId+role+documentType;				   
					AuditLevelDocumentDetails auditLevelDocumentDetails =  new AuditLevelDocumentDetails();
					auditLevelDocumentDetails.setLegalEntityCode(legalEntityCode);
					auditLevelDocumentDetails.setAuditTypeCode(auditTypeCode); 
					auditLevelDocumentDetails.setAuditId(auditId);
					auditLevelDocumentDetails.setPlanId(planId);
					auditLevelDocumentDetails.setDocumentType(documentType); 
					auditLevelDocumentDetails.setDocumentName(documentName);					
					auditLevelDocumentDetails.setDocumentSubType("");  
					auditLevelDocumentDetails.setMaker(maker);  			 
					auditLevelDocumentDetails.setMakerTimestamp(new Timestamp(System.currentTimeMillis()));
					auditLevelDocumentDetails.setUserRoleId(role);					
					auditLevelDocumentDetails.setUnitCode(unitCode);
					auditLevelDocumentDetails.setSeqId("");
					auditLevelDocumentDetails.setUploadStatus(BankAuditConstant.STATUS_INACTIVE);
					 
					String statusMessage =  ifcEnsureBaasDataOfflineUploadService.uploadAuditRatingComplianceObsScore(auditLevelDocumentDetails, files, fileName, ratingComplianceStatus);
					
	 				if(statusMessage.equalsIgnoreCase(BankAuditConstant.SUCCESS)){						
						serviceStatus.setStatus("success");
						serviceStatus.setMessage("successfully uploaded");
					}else if(statusMessage.equalsIgnoreCase(BankAuditConstant.VALIDATION_FAILED)){
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("Validation failed, please check Inspection Id and Inspection Type");
					}else if(statusMessage.equalsIgnoreCase("Failure")){
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("Weightage update failure during Error of Approximation ");
					}else{
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("failed to upload excel");
					}
					 
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("Invalid payload");
				}
				
			} catch (Exception e) {
				logger.error(e.getStackTrace());
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
			return serviceStatus;
		}
		
		/*****************/
		
@RequestMapping(value="/viewAuditLevelCSVDocumentData" ,method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
		DataTableResponse  viewAuditLevelCSVDocumentData(					
				@RequestParam("draw") String drawStr,
				@RequestParam("length") String length,
				@RequestParam("start") String start,
				@RequestParam("search[value]") String search,
				@RequestParam("order[0][column]") String orderColumnStr,
				@RequestParam("order[0][dir]") String orderDirection,
				@RequestParam("legalEntityCode")Integer legalEntityCode,
				@RequestParam("auditId")String auditId, 
				@RequestParam("auditTypeCode")String auditTypeCode, 
				@RequestParam(value="stageOfFile")String stageOfFile,
				@RequestParam(value="referenceNo")Integer referenceNo
				)  {
			
			DataTableResponse listIfcEnsureBaasData = null;
			if (!BankAuditUtil.isEmptyString(drawStr) && !BankAuditUtil.isEmptyString(length)
					&& !BankAuditUtil.isEmptyString(start)) {
				try {
					Integer draw = Integer.parseInt(drawStr);
					Integer size = Integer.parseInt(length);
					Integer page = Integer.parseInt(start) / size;
					Integer orderColumn = null;
					if (!BankAuditUtil.isEmptyString(orderColumnStr)) {
						orderColumn = Integer.parseInt(orderColumnStr);
					} 		
					listIfcEnsureBaasData =	ifcEnsureBaasDataService.viewAuditLevelCSVDocument(legalEntityCode, auditTypeCode, auditId, stageOfFile, referenceNo, search, 
							orderColumn, orderDirection, page, size);
			  
				} catch (Exception e) {
					listIfcEnsureBaasData = new DataTableResponse();
					listIfcEnsureBaasData.setError(e.getMessage());
					logger.error(e.getStackTrace());
				}
			} else {
				listIfcEnsureBaasData = new DataTableResponse();
				listIfcEnsureBaasData.setError("invalid data");
			}
			
			return listIfcEnsureBaasData;
		}
		
		
}
