package com.bankaudit.rest.process.controller;

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.HashMap;
import java.util.List;
import java.util.Map;

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.PathVariable;
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.AuditObservationDto;
import com.bankaudit.dto.process.AuditObservationRiskDto;
import com.bankaudit.process.model.AuditDocumentDetails;
import com.bankaudit.process.model.AuditObservation;
import com.bankaudit.process.model.AuditObservationReportReviewCapture;
import com.bankaudit.process.model.AuditObservationRespondReviewCapture;
import com.bankaudit.rest.process.service.AuditObservationService;
import com.bankaudit.service.SequenceAppenderService;
import com.bankaudit.util.BankAuditUtil;
import com.bankaudit.util.ServiceStatus;




@RestController

@RequestMapping("/api/auditObservation")
public class AuditObservationController {
	
	@Autowired
	AuditObservationService auditObservationService;
	

	@Autowired
	SequenceAppenderService sequenceAppenderService;
	
	
	 private static final int BUFFER_SIZE = 4096;
	 
	static final Logger logger = Logger.getLogger(AuditObservationController.class);	
	
	
@RequestMapping(value = "/getObservations", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	DataTableResponse getAuditSchedules(
			@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")String legalEntityCodeStr,
			@RequestParam("auditId")String auditId,
			@RequestParam("planId")String planId,
			@RequestParam("auditTypeCode")String auditTypeCode,
			@RequestParam("userId")String userId){

		DataTableResponse dataTableResponse = 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);
				}
				
				dataTableResponse = auditObservationService.getAuditObservationList(Integer.parseInt(legalEntityCodeStr),planId,auditId,search, orderColumn, orderDirection, page, size, userId);
				
				dataTableResponse.setDraw(draw);

			} catch (Exception e) {
				dataTableResponse = new DataTableResponse();
				dataTableResponse.setError(e.getMessage());
				logger.error(e.getStackTrace());
			}

		} else {
			dataTableResponse = new DataTableResponse();
			dataTableResponse.setError("invalid data");
		}

		return dataTableResponse;
	}
	
	
@RequestMapping(method=RequestMethod.POST,consumes=MediaType.APPLICATION_JSON_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus createObservation(@RequestBody AuditObservationDto auditObservationDto){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(auditObservationDto!=null
				&& auditObservationDto.getAuditObservations()!=null
				&& !auditObservationDto.getAuditObservations().isEmpty()){
			try {
				
				auditObservationService.createObservation(auditObservationDto);
				serviceStatus.setStatus("success");
				serviceStatus.setMessage("successsfully saved");
			} catch (Exception e) {
				
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
				logger.error(e.getStackTrace());
			}
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("at least one observation is required ");
		}
		
		return serviceStatus; 
	}

	
@RequestMapping(method=RequestMethod.PUT,consumes=MediaType.APPLICATION_JSON_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus updateObservation(@RequestBody AuditObservationDto auditObservationDto){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(auditObservationDto!=null
				&& auditObservationDto.getAuditObservations()!=null
				&& !auditObservationDto.getAuditObservations().isEmpty()){
			try {
				
				serviceStatus.setResult(auditObservationService.updateObservation(auditObservationDto));
				serviceStatus.setStatus("success");
				serviceStatus.setMessage("successsfully updated");
			} catch (Exception e) {
				e.printStackTrace(System.out);
				logger.error(e.getStackTrace());
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("at least one observation is required ");
		}
		
		return serviceStatus; 
	}
		
		
	
@RequestMapping(value="/getByObservationGroupId/{legalEntityCode}/{observationGroupId}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getObservationByObservationGroupId(@PathVariable("observationGroupId")String observationGroupId,
			@PathVariable("legalEntityCode")Integer legalEntityCode){
		
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(!BankAuditUtil.isEmptyString(observationGroupId)
				&& legalEntityCode!=null){
			
			try {
				List<AuditObservation> auditObservations=auditObservationService.getObservationByObservationGroupId(observationGroupId,legalEntityCode);
			
				if(auditObservations!=null && !auditObservations.isEmpty()){
					serviceStatus.setResult(auditObservations);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfully got the list");
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("no observations found");
				}
					
			} catch (Exception e) {

				logger.error(e.getStackTrace());
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
				
			}
			
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage(" Grp id is required ");
		}
		
		
		return serviceStatus; 
	}
	
	/*
@RequestMapping(value="/uploadDocument" ,method=RequestMethod.POST,consumes=MediaType.MULTIPART_FORM_DATA_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus uploadDocument(
			@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="planId")String planId,
			@RequestParam(value="auditId")String auditId,
			@RequestParam(required=false,value="observationId")String observationId,
			@RequestParam(value="documentType")String documentType,
			@RequestParam(value="warningCheck")String warningCheck
			
			
			){
	
		ServiceStatus serviceStatus=new ServiceStatus();
		Map<String, Object> result=new HashMap<>();
		try {
			if(files!=null
					){
				
				List<AuditDocumentDetails> auditDocumentDetails=auditObservationService.getAuditDocumentDetails(legalEntityCode,auditTypeCode,planId,
						auditId,observationId,role+"-"+documentType);
				
				if(BankAuditUtil.isEmptyString(observationId) || observationId.equalsIgnoreCase("null")){
					observationId=sequenceAppenderService.getAutoSequenceId();
					result.put("observationId",observationId);
				}else {
					//result.put("observationId","");
					result.put("observationId",observationId);  // observationId returned as is if Obs Id already present on 10-Sep-19
				}
				
				String fileName=legalEntityCode.toString()+auditTypeCode+planId+auditId+observationId+role+documentType;
				
				Boolean isWarning=false;
				String duplicateFileNames="";
				List<Integer> duplicateDocIds=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;
					}
					
					if(warningCheck.equalsIgnoreCase("yes") && auditDocumentDetails!=null){
						
						for (AuditDocumentDetails auditDocumentDetail : auditDocumentDetails) {
		                  
							if(auditDocumentDetail.getReferencePath().contains(fileName+"_"+commonsMultipartFile.getOriginalFilename())){
								
								isWarning=true;
								duplicateFileNames=duplicateFileNames+" "+commonsMultipartFile.getOriginalFilename();
								duplicateDocIds.add(auditDocumentDetail.getId());
							}
							
						}
						
						
						
					}
					
				}
				
				if(isWarning){
					serviceStatus.setStatus("warning");
				    serviceStatus.setMessage("file " + duplicateFileNames + "  already exist do you want to replace  ");
				    serviceStatus.setResult(duplicateDocIds);
				    return serviceStatus;
				}
				
				
				
				result.put("documentUploadId", auditObservationService.uploadDocument(maker,role,files,fileName));
				
				
				
				serviceStatus.setResult(result);
				serviceStatus.setStatus("success");
				serviceStatus.setMessage("successfully uploaded");
			}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="/getAuditDocumentDetails" ,method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getAuditDocumentDetails(
			@RequestParam(value="legalEntityCode")Integer legalEntityCode,
			@RequestParam(value="auditTypeCode")String auditTypeCode,
			@RequestParam(value="planId")String planId,
			@RequestParam(value="auditId")String auditId,
			@RequestParam(value="observationId")String observationId,
			@RequestParam(value="documentType")String documentType
			){
	
		ServiceStatus serviceStatus=new ServiceStatus();
		
		try {
			
			List<AuditDocumentDetails> auditDocumentDetails=auditObservationService.getAuditDocumentDetails(legalEntityCode,auditTypeCode,planId,
					auditId,observationId,documentType);
			
			if(auditDocumentDetails!=null && !auditDocumentDetails.isEmpty()){
				serviceStatus.setResult(auditDocumentDetails);
				serviceStatus.setStatus("success");
				serviceStatus.setMessage("successfully got the result ");
				
			}else {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("No docs found ");
			}
			
		} catch (Exception e) {
			logger.error(e.getStackTrace());
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("failure");
		}
		return serviceStatus;
	}*/
	
	/* 
@RequestMapping(value="/downloadDocument",method = RequestMethod.GET)
	    public void  downloadProfileFormat(
	    		@RequestParam(value="id",required=true)Integer id,
	    		@RequestParam(value="legalEntityCode",required=true)Integer legalEntityCode,
	    		@RequestParam(value="auditTypeCode",required=true)String auditTypeCode,
	    		@RequestParam(value="planId",required=true)String planId,
	    		@RequestParam(value="auditId",required=true)String auditId,
	    		@RequestParam(value="observationId",required=true)String observationId,
	    		@RequestParam(value="documentType",required=true)String documentType,
	    		
	    		HttpServletRequest request,
	            HttpServletResponse response) throws IOException {    	
	    	
	    	ServletContext context=request.getServletContext();
	    	
	    	AuditDocumentDetails auditDocumentDetails=auditObservationService.getAuditDocumentDetails(id,legalEntityCode,
	    			auditTypeCode,planId,auditId,observationId,documentType);
	    	
				if(auditDocumentDetails!=null){
				
			    	String filePath=auditDocumentDetails.getReferencePath();
			    	
			    	if(!BankAuditUtil.isEmptyString(filePath)){
			    		
			    		File file=new File(filePath);
			    		
			    		if(file.isFile()){
			    			
			    			
			    			 FileInputStream inputStream = new FileInputStream(file);

			          	   
			                 // get MIME type of the file
			                 String mimeType = context.getMimeType(filePath);
			                 


			                 if (mimeType == null) {
			                     // set to binary type if MIME mapping not found
			                     mimeType = "application/octet-stream";
			                 }
			              
			                 // 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="/get",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
		ServiceStatus getAuditObservation(
				@RequestParam("legalEntityCode")Integer legalEntityCode,
				@RequestParam("auditTypeCode")String auditTypeCode,
				@RequestParam("planId")String planId,
				@RequestParam("auditId")String auditId,
				@RequestParam("groupObservationId")String groupObservationId,
				@RequestParam("observationId")String observationId
				){
			
			ServiceStatus serviceStatus=new ServiceStatus();
			
			if(!BankAuditUtil.isEmptyString(observationId)
					&& legalEntityCode!=null){
				
				try {
					AuditObservation auditObservation=auditObservationService.getAuditObservation(legalEntityCode,auditTypeCode
							,planId,auditId,groupObservationId,observationId);
				
					if(auditObservation!=null){
						serviceStatus.setResult(auditObservation);
						serviceStatus.setStatus("success");
						serviceStatus.setMessage("successfully got the AuditObservation");
					}else {
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("no observations found");
					}
						
				} catch (Exception e) {

					e.printStackTrace();
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("failure");
					
				}
			}else {
				
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("Invalid payload");
			}
			
			
			return serviceStatus; 
		}
		
		
@RequestMapping(value="/updateResponse",method=RequestMethod.PUT,consumes=MediaType.APPLICATION_JSON_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)
		ServiceStatus updateResponseObservation(@RequestBody AuditObservation auditObservation){
			ServiceStatus serviceStatus=new ServiceStatus();
			
			if(auditObservation!=null){
				try {
					Map result = new HashMap<String,Object>();
					result.put("respondReviewCaptureId", auditObservationService.updateResponseObservation(auditObservation));
					serviceStatus.setResult(result);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successsfully updated");
				} catch (Exception e) {
					e.printStackTrace();
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("failure");
				}
			}else {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("payload  not valid");
			}
			
			return serviceStatus; 
		}
		
		
@RequestMapping(value="/validateAccObsMapping",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
		ServiceStatus validateAccObsMapping(
				@RequestParam("legalEntityCode")Integer legalEntityCode,
				@RequestParam("auditTypeCode")String auditTypeCode,
				@RequestParam("planId")String planId,
				@RequestParam("auditId")String auditId,
				@RequestParam("custId")String custId,
				@RequestParam("accountNo")String accountNo,
				@RequestParam(value="captureType", required=false)String captureType,
				@RequestParam("mappingId")String mappingId,
				@RequestParam(value="miscType",required=false)String type
				){
			 
			ServiceStatus serviceStatus=new ServiceStatus();
			
			if(!BankAuditUtil.isEmptyString(auditTypeCode) && !BankAuditUtil.isEmptyString(planId)
					&& !BankAuditUtil.isEmptyString(auditId) && !BankAuditUtil.isEmptyString(custId) && !BankAuditUtil.isEmptyString(accountNo) 
					&& legalEntityCode !=null){
				
				try {
					Map grpObsId_ObsIdmap=auditObservationService.validateAccObsMapping(legalEntityCode,auditTypeCode,planId,auditId, custId,accountNo,captureType, mappingId, type);
				
					if(grpObsId_ObsIdmap !=null ){
						serviceStatus.setResult(grpObsId_ObsIdmap);
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("The Observation is already registered for the Account number ");
					}else {
						serviceStatus.setStatus("success");
						serviceStatus.setMessage("No entries till now.");
					}
						
				} catch (Exception e) {

					e.printStackTrace();
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("failure");
					
				}
			}else {
				
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("Invalid payload");
			}
			
			
			return serviceStatus; 
		}
		
		//******************** NABARD RISK Related Services started here *********************************//
		
		
@RequestMapping(value="/insertUpdateAutoBulkRiskCapture",method=RequestMethod.PUT,produces=MediaType.APPLICATION_JSON_VALUE)
		ServiceStatus insertUpdateAutoBulkRiskCapture(
				@RequestParam("legalEntityCode")Integer legalEntityCode,
				@RequestParam("auditTypeCode")String auditTypeCode,
				@RequestParam("planId")String planId,
				@RequestParam("auditId")String auditId,
				@RequestParam("userId")String userId){
			ServiceStatus serviceStatus=new ServiceStatus();
			
			logger.info("Inside Contrlr insertUpdateAutoBulkRiskCapture ..  ..");
			if(!BankAuditUtil.isEmptyString(auditTypeCode) && !BankAuditUtil.isEmptyString(planId)
					&& !BankAuditUtil.isEmptyString(auditId) && !BankAuditUtil.isEmptyString(userId) && legalEntityCode !=null) {
				try {
					List<AuditObservation> auditObservationLst = auditObservationService.getAllPossibleRisk(legalEntityCode, auditTypeCode, auditId, planId, userId);
					if(auditObservationLst !=null && auditObservationLst.size() >0) {
						try {
						auditObservationService.insertBulkRiskCapture(auditObservationLst);
						serviceStatus.setStatus("success");
						serviceStatus.setMessage("successsfully Inserted ");
						} catch (Exception e) {
							serviceStatus.setStatus("failure");
							serviceStatus.setMessage("failure");
							logger.error(e.getStackTrace());
						}
					}else {
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("No records to Insert ");
					}
				} catch (Exception e) {
					e.printStackTrace();
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("failure");
				}
			}else {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("payload  not valid");
			}
			
			return serviceStatus; 
		}
		
		
@RequestMapping(value="/getRiskDtlsByRiskId/{legalEntityCode}/{auditId}/{observationId}/{userId}/{status}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
		ServiceStatus getRiskDtlsByRiskId(@PathVariable("observationId")String observationId,
				@PathVariable("legalEntityCode")Integer legalEntityCode, @PathVariable("auditId")String auditId,
				@PathVariable("userId")String userId, @PathVariable("status")String status){
			
			logger.info("Inside getRiskDtlsByRiskId .."+ legalEntityCode +" auditId.."+auditId +" observationId.."+ observationId +" userId.."+userId +" status.."+status);
			ServiceStatus serviceStatus=new ServiceStatus();
			
			if(!BankAuditUtil.isEmptyString(observationId) && !BankAuditUtil.isEmptyString(auditId)
					&& legalEntityCode!=null){
				
				try {
					AuditObservation auditObservations=auditObservationService.getRiskDtlsByRiskId(legalEntityCode,auditId,observationId, userId, status);
					logger.info("Risk details .."+ auditObservations);
					if(auditObservations!=null){
						serviceStatus.setResult(auditObservations);
						serviceStatus.setStatus("success");
						serviceStatus.setMessage("successfully got the list");
					}else {
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("no observations found");
					}
						
				} catch (Exception e) {

					logger.error(e.getStackTrace());
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("failure");
					
				}
				
			}else {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure ");
			}
		return serviceStatus; 
		}
		
		
@RequestMapping(value="/updateRiskDetails",method=RequestMethod.PUT,consumes=MediaType.APPLICATION_JSON_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)
		ServiceStatus updateRiskDetails(@RequestBody AuditObservationRiskDto auditObservationRiskDto){
			ServiceStatus serviceStatus=new ServiceStatus();
			
			logger.info("Inside updateRiskDetails .."+ auditObservationRiskDto);
			if(auditObservationRiskDto!=null
					&& auditObservationRiskDto.getAuditObservation()!=null
					){
				try {
					
					auditObservationService.updateRiskDetails(auditObservationRiskDto);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successsfully updated");
				} catch (Exception e) {
					logger.error(e.getStackTrace());
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("failure");
				}
			}else {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("at least one observation is required ");
			}
			
			return serviceStatus; 
		}
		
	//************************* NABARD Risk related Services End here  ******************************//
		
	//************************* BaaSDOS Related changes ************************************//
		
@RequestMapping(value="/insertUpdateAutoBulkCheckListCapture",method=RequestMethod.PUT,produces=MediaType.APPLICATION_JSON_VALUE)
		ServiceStatus insertUpdateAutoBulkCheckListCapture(
				@RequestParam("legalEntityCode")Integer legalEntityCode,
				@RequestParam("auditTypeCode")String auditTypeCode,
				@RequestParam("planId")String planId,
				@RequestParam("auditId")String auditId,
				@RequestParam("userId")String userId){
			ServiceStatus serviceStatus=new ServiceStatus();
			
			logger.info("Inside Contrlr insertUpdateAutoBulkCheckListCapture ..  ..");
			if(!BankAuditUtil.isEmptyString(auditTypeCode) && !BankAuditUtil.isEmptyString(planId)
					&& !BankAuditUtil.isEmptyString(auditId) && !BankAuditUtil.isEmptyString(userId) && legalEntityCode !=null) {
				try {
					logger.info("Inside .. ..");
					List<AuditObservation> auditObservationLst = auditObservationService.getAllPossibleMapping(legalEntityCode, auditTypeCode, auditId, planId, userId);
					if(auditObservationLst !=null && auditObservationLst.size() >0) {
						try {
						// auditObservationService.insertBulkRiskCapture(auditObservationLst); // Commented as RiskControl and Control Gap not there, this is part of RCSA
						auditObservationService.insertBulkObservationCapture(auditObservationLst, legalEntityCode, auditTypeCode, auditId, planId); //						
						serviceStatus.setStatus("success");
						serviceStatus.setMessage("successsfully Inserted ");
						} catch (Exception e) {
							serviceStatus.setStatus("failure");
							serviceStatus.setMessage("failure");
							logger.error(e.getStackTrace());
						}
					}else {
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("No records to Insert ");
					}
				} catch (Exception e) {
					e.printStackTrace();
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("failure");
				}
			}else {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("payload  not valid");
			}
			
			return serviceStatus; 
		}
		
		
		
@RequestMapping(value="/getAuditObservation" ,method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
		ServiceStatus getAuditObservation(
				@RequestParam(value="legalEntityCode")String legalEntityCodeStr,
				@RequestParam(value="auditId")String auditId,
				@RequestParam(value="auditTypeCode")String auditTypeCode, 
				@RequestParam(value="observationId")String observationId,
				@RequestParam(value="groupObservationId")String groupObservationId
				
				){
		
			ServiceStatus serviceStatus=new ServiceStatus();
			
			try {			
				AuditObservation auditObservation=auditObservationService.getInspectionObservation(Integer.parseInt(legalEntityCodeStr),auditId, auditTypeCode, groupObservationId, observationId);			
				if(auditObservation!=null){
					serviceStatus.setResult(auditObservation);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfully got the result ");
					
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("No docs found ");
				}
				
			} catch (Exception e) {
				logger.error(e.getStackTrace());
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
			return serviceStatus;
		}
		
		
@RequestMapping(value="/getObservationReportReviewCaptureRemark" ,method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
		ServiceStatus getObservationReportReviewCaptureRemark(
				@RequestParam(value="legalEntityCode")String legalEntityCodeStr, 
				@RequestParam(value="observationId")String observationId){
		
			ServiceStatus serviceStatus=new ServiceStatus();
			
			try {			
				List<AuditObservationReportReviewCapture> auditObservationRemarks=auditObservationService.getObservationReportReviewCaptureRemark(legalEntityCodeStr, observationId);			
				if(auditObservationRemarks!=null){
					serviceStatus.setResult(auditObservationRemarks);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfully got the result ");
					
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("No RemarksFound found ");
				}
				
			} catch (Exception e) {
				logger.error(e.getStackTrace());
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
			return serviceStatus;
		}
		
		//Service to Save or update a particular observation
		
@RequestMapping(value="/updateIndividualObservation" ,method=RequestMethod.PUT,consumes=MediaType.APPLICATION_JSON_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)
		ServiceStatus updateIndividualObservation(@RequestBody AuditObservationDto auditObservationDto){
			ServiceStatus serviceStatus=new ServiceStatus();
			
			if(auditObservationDto!=null && auditObservationDto.getAuditObservations()!=null && !auditObservationDto.getAuditObservations().isEmpty() 
					&& !BankAuditUtil.isEmptyString(auditObservationDto.getGroupObservationId())){
				try {
					
					serviceStatus.setResult(auditObservationService.updateIndividualObservation(auditObservationDto));
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successsfully updated");
				} catch (Exception e) {
					logger.error(e.getStackTrace());
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("failure");
				}
			}else {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("at least one observation is required ");
			}
			
			return serviceStatus; 
		}
		
		//Service to update a individual observation/checklist
		
@RequestMapping(value="/updateObservationSpecificField/{field-to-update}" ,method=RequestMethod.PUT,consumes=MediaType.APPLICATION_JSON_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)
		ServiceStatus updateObservationSpecificField(@RequestBody AuditObservation auditObservation, @PathVariable("field-to-update") String fieldToUpdate){
			ServiceStatus serviceStatus=new ServiceStatus();
			
			if(auditObservation!=null && auditObservation.getAuditId()!=null && auditObservation.getLegalEntityCode() !=null && auditObservation.getAuditTypeCode() !=null 
					&& auditObservation.getObservationId() !=null && auditObservation.getGroupObservationId() !=null && auditObservation.getPlanId() !=null){
				try {
					
					serviceStatus.setResult(auditObservationService.updateObservationSpecificField(auditObservation, fieldToUpdate));
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successsfully updated");
				} catch (Exception e) {
					logger.error(e.getStackTrace());
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("failure");
				}
			}else {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("at least one observation is required ");
			}
			
			return serviceStatus; 
		}
		
		/*
@RequestMapping(value="/uploadIndividualObservationDocument" ,method=RequestMethod.POST,consumes=MediaType.MULTIPART_FORM_DATA_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)
		ServiceStatus  uploadIndividualObservationDocument(
				@RequestParam(value="maker")String maker,
				@RequestParam(value="checker")String checker,
				@RequestParam(value="role")String role,
				@RequestParam(value="files")CommonsMultipartFile[] files,
				@RequestParam(value="legalEntityCode")Integer legalEntityCode,
				@RequestParam(value="auditTypeCode")String auditTypeCode,
				@RequestParam(value="planId")String planId,
				@RequestParam(value="auditId")String auditId,
				@RequestParam(required=false,value="observationId")String observationId,
				@RequestParam(value="documentType")String documentType,
				@RequestParam(value="warningCheck")String warningCheck,
				@RequestParam(value="entityStatus")String entityStatus,
				@RequestParam(value="documentName")String  documentName,
				@RequestParam(value="documentSubType")String  documentSubType)  {
			
			ServiceStatus serviceStatus=new ServiceStatus();
			Map<String, Object> result=new HashMap<>();
			try {
				if(files!=null && observationId!=null){					
					
					List<AuditDocumentDetails> listAuditDocumentDetails=auditObservationService.getAuditDocumentDetails(legalEntityCode,auditTypeCode,planId,auditId,observationId,role+"-"+documentType);					
								 
					result.put("observationId",observationId);  			
					String fileName=legalEntityCode.toString()+auditTypeCode+planId+auditId+observationId+role+documentType;
					
					Boolean isWarning=false;
					String duplicateFileNames="";
					List<Integer> duplicateDocIds=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;
						}
						
						if(warningCheck.equalsIgnoreCase("yes") && listAuditDocumentDetails!=null){							
							for (AuditDocumentDetails auditDocumentDetail : listAuditDocumentDetails) {			                  
								if(auditDocumentDetail.getReferencePath().contains(fileName+"_"+commonsMultipartFile.getOriginalFilename())){									
									isWarning=true;
									duplicateFileNames=duplicateFileNames+" "+commonsMultipartFile.getOriginalFilename();
									duplicateDocIds.add(auditDocumentDetail.getId());
								}								
							}							
						}						
					}
					
					if(isWarning){
						serviceStatus.setStatus("warning");
					    serviceStatus.setMessage("file " + duplicateFileNames + "  already exist do you want to replace  ");
					    serviceStatus.setResult(duplicateDocIds);
					    return serviceStatus;
					}
					
					//result.put("documentUploadId", auditObservationService.uploadDocument(maker,role,files,fileName));
					AuditDocumentDetails auditDocumentDetails =  new AuditDocumentDetails();
					auditDocumentDetails.setLegalEntityCode(legalEntityCode);
					auditDocumentDetails.setAuditTypeCode(auditTypeCode);
					auditDocumentDetails.setPlanId(planId);
					auditDocumentDetails.setAuditId(auditId);
					auditDocumentDetails.setDocumentType(documentType);
					auditDocumentDetails.setEntityStatus(entityStatus);
					auditDocumentDetails.setObservationId(observationId);
					auditDocumentDetails.setMaker(maker);
					auditDocumentDetails.setChecker(checker);
					auditDocumentDetails.setStatus(BankAuditConstant.STATUS_ACTIVE);			
					auditDocumentDetails.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
					auditDocumentDetails.setMakerTimestamp(new Timestamp(System.currentTimeMillis()));
					auditDocumentDetails.setRole(role);
					auditDocumentDetails.setDocumentName(documentName);
					auditDocumentDetails.setDocumentSubType(documentSubType);
					
					result.put("documentUploadId", auditObservationService.uploadIndividualObservationDocument(auditDocumentDetails, files, fileName));
					
					serviceStatus.setResult(result);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfully uploaded");
				}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="/deleteIndividualObservationDocument" ,method=RequestMethod.DELETE,produces=MediaType.APPLICATION_JSON_VALUE)
		ServiceStatus  deleteIndividualObservationDocument(				 
				@RequestParam(value="documentId")String documentId)  {
			ServiceStatus serviceStatus=new ServiceStatus();
			
			if(documentId != null && !BankAuditUtil.isEmptyString(documentId)){
				try{
				   String status =	auditObservationService.deleteIndividualObservationDocument(Integer.parseInt(documentId));
					if(status.equals(BankAuditConstant.SUCCESS)){
						serviceStatus.setStatus("success");
						serviceStatus.setMessage("successfully deleted the selected document");
					}else{
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("failed to delete the selected document");
					}
				}catch (Exception e) {
					logger.error(e.getStackTrace());
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("failure");
				}
			}else{
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("missing parameter value document id");
			} 			
			
			return serviceStatus;
		}*/
		
		/*
@RequestMapping(value="/deleteAllObservationDocument" ,method=RequestMethod.DELETE, produces=MediaType.APPLICATION_JSON_VALUE)
		ServiceStatus deleteAllObservationDocument(
				@RequestParam(value="legalEntityCode")Integer legalEntityCode,
				@RequestParam(value="auditTypeCode")String auditTypeCode,
				@RequestParam(value="planId")String planId,
				@RequestParam(value="auditId")String auditId,
				@RequestParam(value="observationId")String observationId,
				@RequestParam(value="documentType")String documentType
				){
		
			ServiceStatus serviceStatus=new ServiceStatus();
			
			try {
				
				String status = auditObservationService.deleteAllObservationDocument(legalEntityCode, auditTypeCode, planId, auditId, observationId, documentType);
				
				if(status.equals(BankAuditConstant.SUCCESS)){
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfully deleted all the documents");
				}else{
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("failed to delete  documents");
				}
				
			} catch (Exception e) {
				logger.error(e.getStackTrace());
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
			return serviceStatus;
		}*/
		
		
@RequestMapping(value="/getAllNotes" ,method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
		ServiceStatus getAllNotes(
				@RequestParam(value="legalEntityCode")Integer legalEntityCode, 
				@RequestParam(value="observationId")String observationId,
				@RequestParam(value="role")String role 
				){
		
			ServiceStatus serviceStatus=new ServiceStatus();			
			try {
				
				List<AuditObservationReportReviewCapture> listAuditObservationReportReviewCapture = 
						auditObservationService.getObservationReportReviewCaptureNotes(legalEntityCode, observationId, role);
				 
				if(!listAuditObservationReportReviewCapture.isEmpty() && listAuditObservationReportReviewCapture!=null 
						&& listAuditObservationReportReviewCapture.size()>0){
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfully got the notes ");
					serviceStatus.setResult(listAuditObservationReportReviewCapture);
				}else{
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("no notes found for selected observation");
					serviceStatus.setResult(listAuditObservationReportReviewCapture);
				}
				
			} catch (Exception e) {
				logger.error(e.getStackTrace());
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
			return serviceStatus;
		}
		
		
@RequestMapping(value="/getAllRemarks" ,method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
		ServiceStatus getAllRemarks(
				@RequestParam(value="legalEntityCode")Integer legalEntityCode, 
				@RequestParam(value="observationId")String observationId,
				@RequestParam("auditTypeCode") String auditTypeCode,
				@RequestParam("planId") String planId,
				@RequestParam("auditId")String auditId,
				@RequestParam(value="role")String role 
				){
		
			ServiceStatus serviceStatus=new ServiceStatus();			
			try {
				
				List<AuditObservationRespondReviewCapture> listAuditObservationRespondReviewCapture  = 
						auditObservationService.getAuditObservationRespondReviewCapture(legalEntityCode, auditTypeCode, auditId, planId, observationId, role);
				 
				if(!listAuditObservationRespondReviewCapture.isEmpty() && listAuditObservationRespondReviewCapture !=null 
						&& listAuditObservationRespondReviewCapture.size()>0){
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfully got the notes ");
					serviceStatus.setResult(listAuditObservationRespondReviewCapture);
				}else{
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("no remarks found for selected observation"); 
					serviceStatus.setResult(listAuditObservationRespondReviewCapture);
				}
				
			} catch (Exception e) {
				logger.error(e.getStackTrace());
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
			return serviceStatus;
		}
		
		
@RequestMapping(value="/submitObservationNotes" ,method=RequestMethod.PUT, produces=MediaType.APPLICATION_JSON_VALUE)
		ServiceStatus submitObservationNotes(
				@RequestParam(value="legalEntityCode") Integer legalEntityCode,  
				@RequestParam("auditTypeCode") String auditTypeCode,
				@RequestParam("planId") String planId,
				@RequestParam("auditId") String auditId,
				@RequestParam(value="role") String role
				){
		
			ServiceStatus serviceStatus=new ServiceStatus();			
			try{				
				String status = auditObservationService.submitObservationNotes(legalEntityCode, auditTypeCode, auditId, planId, role);
				 
				if(status.equals(BankAuditConstant.SUCCESS)){
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfully submitted observation notes");
				}else{
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("failed to submit observation notes");
				}
				
			}catch (Exception e) {
				logger.error(e.getStackTrace());
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
			return serviceStatus;
		}
		
		// Updating Compliance category of "Others" Section(AuditSubGroup)/Product(Activity)/Process(Product)/Checklist(Finding) to "NA" (Not Applicable) 
		
@RequestMapping(value="/updatingOthersToNA" ,method=RequestMethod.PUT, produces=MediaType.APPLICATION_JSON_VALUE)
		ServiceStatus updatingOthersToNA(
				@RequestParam(value="legalEntityCode") Integer legalEntityCode,  
				@RequestParam("auditTypeCode") String auditTypeCode,
				@RequestParam("auditId") String auditId){
		
			ServiceStatus serviceStatus=new ServiceStatus();			
			try{				
				String status = auditObservationService.updatingOthersToNA(legalEntityCode, auditTypeCode, auditId);
				 
				if(status.equals(BankAuditConstant.SUCCESS)){
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfully Updated the Compliance category of Others cheklist");
				}else if(status.equals(BankAuditConstant.FAILED)){
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("failed to Update the Compliance category of Others cheklist");
				}else {
					serviceStatus.setStatus("success");
					serviceStatus.setMessage(status);
				}
				
			}catch (Exception e) {
				logger.error(e.getStackTrace());
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
			return serviceStatus;
		}
		
		// Method to get Compliance behavior (Non compliance Persistence or not)
		
@RequestMapping(value="/getNonComplianceBehavior" ,method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
		ServiceStatus getNonComplianceBehavior(
				@RequestParam(value="legalEntityCode")Integer legalEntityCode, 
				@RequestParam(value="auditId")String auditId,
				@RequestParam(value="auditTypeCode")String auditTypeCode,
				@RequestParam(value="unitId")String unitId,
				@RequestParam(value="observationId")String observationId,
				@RequestParam(value="mappingId")String mappingId 
				){
		
			ServiceStatus serviceStatus=new ServiceStatus();			
			try {
				
				String nonComplianceBehavior = auditObservationService.getNonComplianceBehavior(legalEntityCode, auditId, auditTypeCode, unitId, observationId, mappingId);
				if(nonComplianceBehavior!=null){
					serviceStatus.setResult(nonComplianceBehavior);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfully got the Non compliance behavior ");
				}else{
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("failure");
				}
				
			} catch (Exception e) {
				logger.error(e.getStackTrace());
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
			return serviceStatus;
		}
		
		
}
