package com.bankaudit.rest.process.service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bankaudit.constants.BankAuditConstant;
import com.bankaudit.dao.GeneralParameterDao;
import com.bankaudit.dto.DataTableResponse;
import com.bankaudit.dto.process.AuditObservationDto;
import com.bankaudit.dto.process.AuditObservationRiskDto;
import com.bankaudit.dto.process.NonCompliancePersistenceChecklistDto;
import com.bankaudit.model.GeneralParameter;
import com.bankaudit.process.model.AuditDocumentDetails;
import com.bankaudit.process.model.AuditDocumentDetailsTemp;
import com.bankaudit.process.model.AuditObservation;
import com.bankaudit.process.model.AuditObservationHst;
import com.bankaudit.process.model.AuditObservationReportReviewCapture;
import com.bankaudit.process.model.AuditObservationRespondReviewCapture;
import com.bankaudit.process.model.AuditSchedule;
import com.bankaudit.process.model.AuditScheduleStatus;
import com.bankaudit.process.model.ControlGapDetails;
import com.bankaudit.process.model.ControlGapDetailsHst;
import com.bankaudit.process.model.RecommendationDetails;
import com.bankaudit.process.model.RecommendationDetailsHst;
import com.bankaudit.process.model.RiskControlDetails;
import com.bankaudit.process.model.RiskControlDetailsHst;
import com.bankaudit.process.model.TaskDetails;
import com.bankaudit.process.model.TaskDetailsHst;
import com.bankaudit.report.v3.service.AuditBookReportServiceV3;
import com.bankaudit.rest.process.dao.AuditObservationDao;
import com.bankaudit.rest.process.dao.ControlGapDetailsDao;
import com.bankaudit.rest.process.dao.RecommendationDetailsDao;
import com.bankaudit.rest.process.dao.RiskControlDetailsDao;
import com.bankaudit.rest.process.dao.TaskDetailsDao;
import com.bankaudit.service.BusinessDateService;
import com.bankaudit.service.SequenceAppenderService;
import com.bankaudit.util.BankAuditUtil;

@Service
@Transactional("transactionManager")
public class AuditObservationServiceImpl implements AuditObservationService {
	
	@Autowired(required=true)
	AuditObservationDao auditObservationDao;
	
	@Autowired
	BusinessDateService businessDateService;
	
	@Autowired
    SequenceAppenderService sequenceAppenderService;
	
	@Autowired
	MyAuditsService  myAuditsService;
	
	@Autowired
	RiskControlDetailsService  riskControlDetailsService;
	
	@Autowired
	ControlGapDetailsService  controlGapDetailsService;
	
	@Autowired
	RecommendationDetailsService  recommendationDetailsService;
	
	@Autowired
	TaskDetailsService  taskDetailsService;
	
	@Autowired
	RiskControlDetailsDao  riskControlDetailsDao;
	
	@Autowired
	ControlGapDetailsDao  controlGapDetailsDao;
	
	@Autowired
	RecommendationDetailsDao  recommendationDetailsDao;
	
	@Autowired
	TaskDetailsDao  taskDetailsDao;
	
	@Autowired
	AuditBookReportServiceV3 auditBookReportServiceV3;
	
	@Autowired
	GeneralParameterDao generalParameterDao;
	
	static final Logger logger = Logger.getLogger(AuditObservationServiceImpl.class);

	@Override
	public DataTableResponse getAuditObservationList(int legalEntityCode,String planId,String auditId, String search, Integer orderColumn,
			String orderDirection, Integer page, Integer size, String userId) {
		DataTableResponse ds=auditObservationDao.getAuditObservationList(legalEntityCode,planId,auditId,search,orderColumn,
				orderDirection,page,size, userId);
		return ds;
	}

	@Override
	public void createObservation(AuditObservationDto auditObservationDto) {
		
		List<AuditObservation> auditObservations=auditObservationDto.getAuditObservations();
		
		
		String groupObservationId ="";
		if(BankAuditUtil.isEmptyString(auditObservations.get(0).getGroupObservationId())){
			groupObservationId= sequenceAppenderService.getAutoSequenceId();
		}else {
			groupObservationId=auditObservations.get(0).getGroupObservationId();
		}
		
		
		if(auditObservationDto.getDuplicateDocIds()!=null){
			
			for (Integer  duplicateDocId : auditObservationDto.getDuplicateDocIds()) {
				auditObservationDao.deleteById(AuditDocumentDetails.class, duplicateDocId);
			}
			
		}
		
		AuditDocumentDetailsTemp auditDocumentDetailsTemp=null;
		if(auditObservationDto.getDocumentUploadId()!=null){
			auditDocumentDetailsTemp=(AuditDocumentDetailsTemp) auditObservationDao.get(AuditDocumentDetailsTemp.class, 
					auditObservationDto.getDocumentUploadId());
			AuditDocumentDetails auditDocumentDetails=null;


			if(auditDocumentDetailsTemp!=null){
				for (String url : auditDocumentDetailsTemp.getUrls().split(BankAuditConstant.DELIMITER_URL)) {
					auditDocumentDetails=new AuditDocumentDetails();
					auditDocumentDetails.setLegalEntityCode(auditObservationDto.getAuditObservations().get(0).getLegalEntityCode());
					auditDocumentDetails.setAuditTypeCode(auditObservationDto.getAuditObservations().get(0).getAuditTypeCode());
					auditDocumentDetails.setPlanId(auditObservationDto.getAuditObservations().get(0).getPlanId());
					auditDocumentDetails.setAuditId(auditObservationDto.getAuditObservations().get(0).getAuditId());
					auditDocumentDetails.setDocumentType(auditDocumentDetailsTemp.getRole()+"-G");
					auditDocumentDetails.setEntityStatus(auditObservationDto.getAuditObservations().get(0).getEntityStatus());
					auditDocumentDetails.setStatus("A");
					auditDocumentDetails.setMaker(auditObservationDto.getAuditObservations().get(0).getMaker());
		            auditDocumentDetails.setChecker(auditObservationDto.getAuditObservations().get(0).getChecker());
					auditDocumentDetails.setBusinessdateTimestamp(auditObservationDto.getAuditObservations().get(0).getBusinessdateTimestamp());
					auditDocumentDetails.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
					auditDocumentDetails.setMakerTimestamp(auditDocumentDetails.getBusinessdateTimestamp());
					auditDocumentDetails.setReferencePath(url);
					
					auditDocumentDetails.setObservationId(groupObservationId);
					
					
					auditObservationDao.save(auditDocumentDetails);
				}
				auditObservationDao.delete(auditDocumentDetailsTemp);
			}
		}
		
	
		for (AuditObservation auditObservation : auditObservations) {
			auditObservation.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(auditObservation.getLegalEntityCode()));
			auditObservation.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
			auditObservation.setMakerTimestamp(auditObservation.getBusinessdateTimestamp());
			if(BankAuditUtil.isEmptyString(auditObservation.getObservationId())){
				auditObservation.setObservationId(sequenceAppenderService.getAutoSequenceId());
			}
			auditObservation.setGroupObservationId(groupObservationId);
			auditObservationDao.flushSession();
			auditObservationDao.save(auditObservation);

			
			if(auditObservation.getDuplicateDocIds()!=null){
				
				for (Integer  duplicateDocId : auditObservation.getDuplicateDocIds()) {
					auditObservationDao.deleteById(AuditDocumentDetails.class, duplicateDocId);
				}
				
			}
			
			
			if(auditObservation.getDocumentUploadId()!=null){
				auditDocumentDetailsTemp=(AuditDocumentDetailsTemp) auditObservationDao.get(AuditDocumentDetailsTemp.class, 
						auditObservation.getDocumentUploadId());
				
				
				for (String url : auditDocumentDetailsTemp.getUrls().split(BankAuditConstant.DELIMITER_URL)) {

					AuditDocumentDetails auditDocumentDetails=new AuditDocumentDetails();
					auditDocumentDetails.setLegalEntityCode(auditObservation.getLegalEntityCode());
					auditDocumentDetails.setAuditTypeCode(auditObservation.getAuditTypeCode());
					auditDocumentDetails.setPlanId(auditObservation.getPlanId());
					auditDocumentDetails.setAuditId(auditObservation.getAuditId());
					auditDocumentDetails.setDocumentType(auditDocumentDetailsTemp.getRole()+"-S");
					auditDocumentDetails.setEntityStatus(auditObservation.getEntityStatus());
					auditDocumentDetails.setStatus("A");
					auditDocumentDetails.setMaker(auditObservation.getMaker());
		            auditDocumentDetails.setChecker(auditObservation.getChecker());
					auditDocumentDetails.setBusinessdateTimestamp(auditObservation.getBusinessdateTimestamp());
					auditDocumentDetails.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
					auditDocumentDetails.setMakerTimestamp(auditDocumentDetails.getBusinessdateTimestamp());
					auditDocumentDetails.setReferencePath(url);
					auditDocumentDetails.setObservationId(auditObservation.getObservationId());
					auditObservationDao.save(auditDocumentDetails);
				}
				auditObservationDao.delete(auditDocumentDetailsTemp);
			}
			
		  
		}
		AuditObservation auditObservation=auditObservations.get(0);
		if(auditObservation.getSubmissionStatus().equalsIgnoreCase("A")){
			AuditSchedule auditSchedule=getObservationCounts(auditObservation.getLegalEntityCode(), auditObservation.getAuditTypeCode(), auditObservation.getPlanId(), auditObservation.getAuditId());
			auditSchedule.setLegalEntityCode(auditObservation.getLegalEntityCode());
			auditSchedule.setAuditTypeCode(auditObservation.getAuditTypeCode());
			auditSchedule.setPlanId(auditObservation.getPlanId());
			auditSchedule.setAuditId(auditObservation.getAuditId());
			myAuditsService.updateAuditScheduleCounts(auditSchedule);
		}
		
	}
 
	@SuppressWarnings("unchecked")
	@Override
	public String updateObservation(AuditObservationDto auditObservationDto) {
		
			long start0 = System.currentTimeMillis();
			long start = System.currentTimeMillis();
		AuditDocumentDetailsTemp auditDocumentDetailsTemp=null;
		List<AuditObservation> auditObservations=auditObservationDto.getAuditObservations();
		logger.info("1:: After obs .. "+ ((System.currentTimeMillis()-start)/1000));
		
			start = System.currentTimeMillis();
		String groupObservationId="";
		if(BankAuditUtil.isEmptyString(auditObservationDto.getGroupObservationId())){
			groupObservationId= sequenceAppenderService.getAutoSequenceId();
		}else {
			groupObservationId=auditObservationDto.getGroupObservationId();
		}
			logger.info("2:: Seq .. "+ ((System.currentTimeMillis()-start)/1000));
					
			start = System.currentTimeMillis();
		Map<String,Object> properties=new HashMap<String, Object>();
		properties.put("groupObservationId", groupObservationId);
        List<AuditObservation> auditObservationsStored=
        		auditObservationDao.getEntitiesByMatchingProperties(AuditObservation.class, properties);
        	logger.info("3:: entity prop.. "+ ((System.currentTimeMillis()-start)/1000));
        
        	start = System.currentTimeMillis();
        if(auditObservationsStored!=null){
        	for (AuditObservation auditObservation : auditObservationsStored) {
        		auditObservationDao.save(new AuditObservationHst(auditObservation));
			}
        }
        	logger.info("4:: ObsHst save.."+((System.currentTimeMillis()-start)/1000));
        	start = System.currentTimeMillis();
		auditObservationDao.deleteObservationByGrpId(groupObservationId);
			logger.info("5:: Obs del.."+((System.currentTimeMillis()-start)/1000));
		
		List<String> rolesListInspector = Arrays.asList(("G2,G8,G12").split(","));  //Inspection
		List<String> rolesListCompliance = Arrays.asList(("G3,G31").split(","));	//Compliance or Response
		List<String> rolesListReviewer = Arrays.asList(("G4,G7").split(","));       //review/Scrutiny	
		
		AuditObservation auditObs = auditObservations.get(0);
		Map<String, Object> propertiesSch = new HashMap<>();
		propertiesSch.put("legalEntityCode", auditObs.getLegalEntityCode());
		propertiesSch.put("auditTypeCode", auditObs.getAuditTypeCode());
		propertiesSch.put("planId", auditObs.getPlanId());
		propertiesSch.put("auditId", auditObs.getAuditId());			
		AuditSchedule auditSchedule = (AuditSchedule)auditObservationDao.getUniqueEntityByMatchingProperties(AuditSchedule.class, propertiesSch);
		
		for (AuditObservation auditObservation : auditObservations) {
				start = System.currentTimeMillis();
			auditObservation.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(auditObservation.getLegalEntityCode()));
			auditObservation.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
			if(auditObservation.getObservationId()==null){
				auditObservation.setObservationId(sequenceAppenderService.getAutoSequenceId());
			}
			auditObservation.setGroupObservationId(groupObservationId);
			if(!BankAuditUtil.isEmptyString(auditObservation.getReviewNote())
					&& !BankAuditUtil.isEmptyString(auditObservation.getReviewNoteMaker())){
				auditObservation.setReviewNoteMakerTimestamp(new Timestamp(System.currentTimeMillis()).toString());
			}
			String reviewStatusAttributeLastAuth = null;
			if(!BankAuditUtil.isEmptyString(auditObservation.getReviewOwner())
					&& rolesListReviewer.contains(auditObservation.getRole()) ) {
				if(BankAuditConstant.REVIEW_STATUS_WS.equalsIgnoreCase(auditSchedule.getReviewStatus())){					
					if(BankAuditConstant.STATUS_AUTH.equalsIgnoreCase(auditObservation.getReviewStatus())){	
						reviewStatusAttributeLastAuth = auditObservation.getReviewStatusAttributeLastAuth();
						auditObservation.setReviewStatusAttributeLastAuth(auditObservation.getReviewStatusAttribute());					
					} 					 			
				}								
			} 			
			
			auditObservationDao.flushSession();			
			auditObservationDao.save(auditObservation);
				logger.info("6:: Obs save.."+ ((System.currentTimeMillis()-start)/1000));
			
				/*start = System.currentTimeMillis();
			if(auditObservation.getDuplicateDocIds()!=null){
					for (Integer  duplicateDocId : auditObservation.getDuplicateDocIds()) {
							auditObservationDao.deleteById(AuditDocumentDetails.class, duplicateDocId);
					}					
			}
			logger.info("7:: dup del.."+ ((System.currentTimeMillis()-start)/1000));*/
			
			/*start = System.currentTimeMillis();
			if(auditObservation.getDocumentUploadId()!=null){
					start = System.currentTimeMillis();
				auditDocumentDetailsTemp=(AuditDocumentDetailsTemp) auditObservationDao.get(AuditDocumentDetailsTemp.class, 
						auditObservation.getDocumentUploadId());
				logger.info("8:: get doc.."+ ((System.currentTimeMillis()-start)/1000));
				
					start = System.currentTimeMillis();
				for (String url : auditDocumentDetailsTemp.getUrls().split(BankAuditConstant.DELIMITER_URL)) {
					AuditDocumentDetails auditDocumentDetails=new AuditDocumentDetails();
					auditDocumentDetails.setLegalEntityCode(auditObservation.getLegalEntityCode());
					auditDocumentDetails.setAuditTypeCode(auditObservation.getAuditTypeCode());
					auditDocumentDetails.setPlanId(auditObservation.getPlanId());
					auditDocumentDetails.setAuditId(auditObservation.getAuditId());
					auditDocumentDetails.setDocumentType(auditDocumentDetailsTemp.getRole()+"-S");
					auditDocumentDetails.setEntityStatus(auditObservation.getEntityStatus());
					auditDocumentDetails.setStatus("A");
					auditDocumentDetails.setMaker(auditObservation.getMaker());
		            auditDocumentDetails.setChecker(auditObservation.getChecker());
					auditDocumentDetails.setBusinessdateTimestamp(auditObservation.getBusinessdateTimestamp());
					auditDocumentDetails.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
					auditDocumentDetails.setMakerTimestamp(auditDocumentDetails.getBusinessdateTimestamp());
					auditDocumentDetails.setReferencePath(url);
					auditDocumentDetails.setObservationId(auditObservation.getObservationId());
					auditObservationDao.save(auditDocumentDetails);
				}
				logger.info("8.1:: save doc.."+ ((System.currentTimeMillis()-start)/1000));
				auditObservationDao.delete(auditDocumentDetailsTemp);
			}
			logger.info("9:: doc save del.."+ ((System.currentTimeMillis()-start)/1000));*/
			
			//Call the service to save/update data into audit_observation_report_review_capture_wrk	 
			
			//Not maintaining remarks 
			/*AuditObservationReportReviewCaptureWrk auditObservationReportReviewCaptureWrk = new AuditObservationReportReviewCaptureWrk();			
			auditObservationReportReviewCaptureWrk.setAuditId(auditObservation.getAuditId());
			auditObservationReportReviewCaptureWrk.setAuditTypeCode(auditObservation.getAuditTypeCode());
			auditObservationReportReviewCaptureWrk.setCaptureType(auditObservation.getCaptureType());
			auditObservationReportReviewCaptureWrk.setComment(auditObservation.getFindingRemarks());
			auditObservationReportReviewCaptureWrk.setGroupObservationId(auditObservation.getGroupObservationId());	 
			auditObservationReportReviewCaptureWrk.setLegalEntityCode(auditObservation.getLegalEntityCode());
			auditObservationReportReviewCaptureWrk.setMaker(auditObservation.getMaker());
			auditObservationReportReviewCaptureWrk.setMakerTimestamp(auditObservation.getMakerTimestamp());
			auditObservationReportReviewCaptureWrk.setObservationId(auditObservation.getObservationId());
			auditObservationReportReviewCaptureWrk.setPlanId(auditObservation.getPlanId()); 			
			auditObservationDao.deleteAuditObservationReportReviewCaptureWrk(auditObservationReportReviewCaptureWrk);
			auditObservationDao.save(auditObservationReportReviewCaptureWrk);*/	
			
			/********Code for notes Start ************/	
				start = System.currentTimeMillis();				
			String role = auditObservation.getRole();
			if((!BankAuditUtil.isEmptyString(auditObservation.getObservationNote()) && rolesListInspector.contains(auditObservation.getRole()) )
					|| (!BankAuditUtil.isEmptyString(auditObservation.getReviewNote()) && rolesListReviewer.contains(auditObservation.getRole()) )
					|| (!BankAuditUtil.isEmptyString(auditObservation.getResponseNote()) && rolesListCompliance.contains(auditObservation.getRole()) ) ){
				
				Boolean isNotesSameUser = false ;				 
				
				isNotesSameUser = auditObservationDao.checkIfLatestNoteIsGivenBySameUser(auditObservation);		
				AuditObservationReportReviewCapture auditObservationReportReviewCapture = new AuditObservationReportReviewCapture();			
				if(isNotesSameUser){
					auditObservationReportReviewCapture = auditObservationDao.getAuditObservationReportReviewCaptureLatest(auditObservation);
					if(auditObservationReportReviewCapture==null ||( auditObservationReportReviewCapture.getId()==null
							|| auditObservationReportReviewCapture.getId()<=0)){
						auditObservationReportReviewCapture = new AuditObservationReportReviewCapture();		
					}
				}						
				
				auditObservationReportReviewCapture.setLegalEntityCode(auditObservation.getLegalEntityCode());
				auditObservationReportReviewCapture.setPlanId(auditObservation.getPlanId()); 			 			
				auditObservationReportReviewCapture.setAuditTypeCode(auditObservation.getAuditTypeCode());
				auditObservationReportReviewCapture.setAuditId(auditObservation.getAuditId());
				auditObservationReportReviewCapture.setObservationId(auditObservation.getObservationId());
				auditObservationReportReviewCapture.setGroupObservationId(auditObservation.getGroupObservationId());		
							
				auditObservationReportReviewCapture.setMakerTimestamp(new Timestamp(System.currentTimeMillis()));				 					
				auditObservationReportReviewCapture.setCaptureType(auditObservation.getRole());				
				auditObservationReportReviewCapture.setIsCurrentCycle(BankAuditConstant.YES);	
				auditObservationReportReviewCapture.setEntityStatus(BankAuditConstant.STATUS_AUTH);
				
				if(rolesListInspector.contains(role)){					
					auditObservationReportReviewCapture.setComment(auditObservation.getObservationNote());
					auditObservationReportReviewCapture.setMaker(auditObservation.getObservationNoteMaker());	
					auditObservationReportReviewCapture.setEntityStatus(BankAuditConstant.STATUS_PENDING_AUTH);
				}
				
				else if(rolesListCompliance.contains(role)){			 
					auditObservationReportReviewCapture.setComment(auditObservation.getResponseNote());
					auditObservationReportReviewCapture.setMaker(auditObservation.getResponseNoteMaker()); 
					if(auditObservation.getResponseStatus().equalsIgnoreCase("A")
							 && auditObservation.getReviewStatus().equalsIgnoreCase("PA") ){
						auditObservationReportReviewCapture.setIsCurrentCycle(BankAuditConstant.NO);								
					}					
				}
				
				else if(rolesListReviewer.contains(role)){			 
					auditObservationReportReviewCapture.setComment(auditObservation.getReviewNote());
					auditObservationReportReviewCapture.setMaker(auditObservation.getReviewNoteMaker());  
					if(auditObservation.getResponseStatus().equalsIgnoreCase("R")
							 && auditObservation.getReviewStatus().equalsIgnoreCase("PA") ){
						auditObservationReportReviewCapture.setIsCurrentCycle(BankAuditConstant.NO);								
					} 
				}  
				 				
				auditObservationDao.flushSession();
				auditObservationDao.saveOrUpdate(auditObservationReportReviewCapture);
			}
				logger.info("10 :: save notes.."+ ((System.currentTimeMillis()-start)/1000));
			/************** Notes End ************************/
			
			/************** Remarks Start *******************/			
			/********Code for Remarks	************/	
				start = System.currentTimeMillis();
			/*if( (!BankAuditUtil.isEmptyString(auditObservation.getReviewRemarks()) &&  !BankAuditUtil.isEmptyString(auditObservation.getReviewOwner() )
					&& rolesListReviewer.contains(auditObservation.getRole()) )
					|| (!BankAuditUtil.isEmptyString(auditObservation.getResponseRemarks()) && !BankAuditUtil.isEmptyString(auditObservation.getResponseOwner()) 
							&& rolesListCompliance.contains(auditObservation.getRole()) ) )*/
			//Get Further compliance value
			String fcValue="";
			if(rolesListReviewer.contains(auditObservation.getRole())){ 
				List<GeneralParameter> gpList = generalParameterDao.getGeneralParameter(auditObservation.getLegalEntityCode(), null, null, "STATUS_REVIEW", "REVIEW_ATTRIBUTE", 
						auditObservation.getReviewStatusAttribute(), null);
				for (GeneralParameter generalParameter : gpList) {
					if(generalParameter.getValue().equalsIgnoreCase(auditObservation.getReviewStatusAttribute())){
						fcValue = generalParameter.getDescription();
						break;
					}
				}
			}
			
			if( (!BankAuditUtil.isEmptyString(auditObservation.getReviewOwner() )
					&& rolesListReviewer.contains(auditObservation.getRole()) )
					|| (!BankAuditUtil.isEmptyString(auditObservation.getResponseRemarks()) && !BankAuditUtil.isEmptyString(auditObservation.getResponseOwner()) 
							&& rolesListCompliance.contains(auditObservation.getRole()) ) ){
				
				List<String> rolesToCheck = new ArrayList<String>();
				if(rolesListCompliance.contains(role)){			 
					rolesToCheck.addAll(rolesListCompliance);	
				}
				else if(rolesListReviewer.contains(role)){			 
					rolesToCheck.addAll(rolesListReviewer);		 
				}
				
				Boolean isSameUser = auditObservationDao.checkIfLatestRemarksIsGivenBySameUserGroup(auditObservation, rolesToCheck);		
				AuditObservationRespondReviewCapture auditObservationRespondReviewCapture = new AuditObservationRespondReviewCapture();			
				if(isSameUser){
					auditObservationRespondReviewCapture = auditObservationDao.getAuditObservationRespondReviewCaptureLatest(auditObservation, rolesToCheck);
					if(auditObservationRespondReviewCapture==null ||( auditObservationRespondReviewCapture.getId()==null
							|| auditObservationRespondReviewCapture.getId()<=0)){
						auditObservationRespondReviewCapture = new AuditObservationRespondReviewCapture();		
					}
				}						
				
				auditObservationRespondReviewCapture.setLegalEntityCode(auditObservation.getLegalEntityCode());
				auditObservationRespondReviewCapture.setPlanId(auditObservation.getPlanId()); 			 			
				auditObservationRespondReviewCapture.setAuditTypeCode(auditObservation.getAuditTypeCode());
				auditObservationRespondReviewCapture.setAuditId(auditObservation.getAuditId());
				auditObservationRespondReviewCapture.setObservationId(auditObservation.getObservationId());
				auditObservationRespondReviewCapture.setGroupObservationId(auditObservation.getGroupObservationId());								
				auditObservationRespondReviewCapture.setMakerTimestamp(new Timestamp(System.currentTimeMillis()));				 					
				auditObservationRespondReviewCapture.setCaptureType(auditObservation.getRole());				 
								 				 
				if(rolesListCompliance.contains(role)){			 
					auditObservationRespondReviewCapture.setComment(auditObservation.getResponseRemarks());
					auditObservationRespondReviewCapture.setMaker(auditObservation.getResponseOwner()); 
					auditObservationRespondReviewCapture.setStatus(auditObservation.getResponseStatus());				
					 
					if(BankAuditConstant.STATUS_AUTH.equalsIgnoreCase(auditObservation.getResponseStatus())){
						Map<String, Object> propertiesSchSt = new HashMap<String, Object>();
						propertiesSchSt.put("legalEntityCode", auditObservation.getLegalEntityCode());
						propertiesSchSt.put("auditTypeCode", auditObservation.getAuditTypeCode());
						propertiesSchSt.put("auditId", auditObservation.getAuditId());
						AuditScheduleStatus auditScheduleStatus = (AuditScheduleStatus) auditObservationDao.getUniqueEntityByMatchingProperties(AuditScheduleStatus.class, propertiesSchSt);		
				 						
						if(auditScheduleStatus!=null && auditScheduleStatus.getPendingWithBank() != null 
								&& auditScheduleStatus.getPendingWithScrutiniser() != null) {
							auditScheduleStatus.setPendingWithBank(auditScheduleStatus.getPendingWithBank()-1);
							auditScheduleStatus.setPendingWithScrutiniser(auditScheduleStatus.getPendingWithScrutiniser()+1);
							auditObservationDao.saveOrUpdate(auditScheduleStatus);
						}
					}					
				}
				else if(rolesListReviewer.contains(role)){			 
					auditObservationRespondReviewCapture.setComment(auditObservation.getReviewRemarks());
					auditObservationRespondReviewCapture.setMaker(auditObservation.getReviewOwner());	
					auditObservationRespondReviewCapture.setStatus(auditObservation.getReviewStatus());
					auditObservationRespondReviewCapture.setReviewRespondStatus(fcValue);
					
					if(BankAuditConstant.STATUS_AUTH.equalsIgnoreCase(auditObservation.getReviewStatus())){
						Map<String, Object> propertiesSchSt = new HashMap<String, Object>();
						propertiesSchSt.put("legalEntityCode", auditObservation.getLegalEntityCode());
						propertiesSchSt.put("auditTypeCode", auditObservation.getAuditTypeCode());
						propertiesSchSt.put("auditId", auditObservation.getAuditId());
						AuditScheduleStatus auditScheduleStatus = (AuditScheduleStatus) auditObservationDao.getUniqueEntityByMatchingProperties(AuditScheduleStatus.class, propertiesSchSt);		
				 			
						// auditScheduleStatus null Check
						if(auditObservation.getReviewStatusAttribute() != null && auditScheduleStatus !=null
								&& auditScheduleStatus.getPendingWithBank() != null
								&& auditScheduleStatus.getPendingWithScrutiniser() != null
								&& auditScheduleStatus.getScrutinyfurtherComplianceAsOn() != null
								&& auditScheduleStatus.getScrutinyAcceptedAsOn() != null ){
							if(auditObservation.getReviewStatusAttribute().equalsIgnoreCase(reviewStatusAttributeLastAuth)
									&& BankAuditConstant.REVIEW_STATUS_ATTRIB_FURTHER_COMPLIANCE.equalsIgnoreCase(auditObservation.getReviewStatusAttribute())){
								auditScheduleStatus.setPendingWithBank(auditScheduleStatus.getPendingWithBank()+1);
								auditScheduleStatus.setPendingWithScrutiniser(auditScheduleStatus.getPendingWithScrutiniser()-1);
							}else if(!auditObservation.getReviewStatusAttribute().equalsIgnoreCase(reviewStatusAttributeLastAuth)
									&& BankAuditConstant.REVIEW_STATUS_ATTRIB_FURTHER_COMPLIANCE.equalsIgnoreCase(auditObservation.getReviewStatusAttribute())){							
								auditScheduleStatus.setPendingWithBank(auditScheduleStatus.getPendingWithBank()+1); 
								auditScheduleStatus.setScrutinyfurtherComplianceAsOn(auditScheduleStatus.getScrutinyfurtherComplianceAsOn()+1);								
								if(BankAuditConstant.REVIEW_STATUS_ATTRIB_ACCEPTED.equalsIgnoreCase(reviewStatusAttributeLastAuth)){
									auditScheduleStatus.setScrutinyAcceptedAsOn(auditScheduleStatus.getScrutinyAcceptedAsOn()-1);
								}else if(BankAuditConstant.REVIEW_STATUS_ATTRIB_CARRY_FORWARD.equalsIgnoreCase(reviewStatusAttributeLastAuth)){
									auditScheduleStatus.setScrutinyCarryForwardAsOn(auditScheduleStatus.getScrutinyCarryForwardAsOn()-1);
								}
							}else if(!auditObservation.getReviewStatusAttribute().equalsIgnoreCase(reviewStatusAttributeLastAuth)
									&& BankAuditConstant.REVIEW_STATUS_ATTRIB_ACCEPTED.equalsIgnoreCase(auditObservation.getReviewStatusAttribute())){
								auditScheduleStatus.setScrutinyAcceptedAsOn(auditScheduleStatus.getScrutinyAcceptedAsOn()+1);
								if(BankAuditConstant.REVIEW_STATUS_ATTRIB_FURTHER_COMPLIANCE.equalsIgnoreCase(reviewStatusAttributeLastAuth)){
									auditScheduleStatus.setScrutinyfurtherComplianceAsOn(auditScheduleStatus.getScrutinyfurtherComplianceAsOn()-1);
									auditScheduleStatus.setPendingWithScrutiniser(auditScheduleStatus.getPendingWithScrutiniser()-1);
								}else if(BankAuditConstant.REVIEW_STATUS_ATTRIB_CARRY_FORWARD.equalsIgnoreCase(reviewStatusAttributeLastAuth)){
									auditScheduleStatus.setScrutinyCarryForwardAsOn(auditScheduleStatus.getScrutinyCarryForwardAsOn()-1);
								}
							}else if(!auditObservation.getReviewStatusAttribute().equalsIgnoreCase(reviewStatusAttributeLastAuth)
									&& BankAuditConstant.REVIEW_STATUS_ATTRIB_CARRY_FORWARD.equalsIgnoreCase(auditObservation.getReviewStatusAttribute())){
								auditScheduleStatus.setScrutinyCarryForwardAsOn(auditScheduleStatus.getScrutinyCarryForwardAsOn()+1);								
								if(BankAuditConstant.REVIEW_STATUS_ATTRIB_ACCEPTED.equalsIgnoreCase(reviewStatusAttributeLastAuth)){
									auditScheduleStatus.setScrutinyAcceptedAsOn(auditScheduleStatus.getScrutinyAcceptedAsOn()-1);
								}else if(BankAuditConstant.REVIEW_STATUS_ATTRIB_FURTHER_COMPLIANCE.equalsIgnoreCase(reviewStatusAttributeLastAuth)){
									auditScheduleStatus.setScrutinyfurtherComplianceAsOn(auditScheduleStatus.getScrutinyfurtherComplianceAsOn()-1);
									auditScheduleStatus.setPendingWithScrutiniser(auditScheduleStatus.getPendingWithScrutiniser()-1);
								}
							}
							auditObservationDao.saveOrUpdate(auditScheduleStatus);
						} // auditScheduleStatus null Check, end here
					}	
				}  				
				
				/*if(!BankAuditUtil.isEmptyString(auditObservation.getReviewRemarks()) 
						&&  !BankAuditUtil.isEmptyString(auditObservation.getReviewOwner())){					
					auditObservationRespondReviewCapture.setComment(auditObservation.getReviewRemarks());
					auditObservationRespondReviewCapture.setMaker(auditObservation.getReviewOwner());					
				}
				else if(!BankAuditUtil.isEmptyString(auditObservation.getResponseRemarks()) 
						&& !BankAuditUtil.isEmptyString(auditObservation.getResponseOwner())) {
					auditObservationRespondReviewCapture.setComment(auditObservation.getResponseRemarks());
					auditObservationRespondReviewCapture.setMaker(auditObservation.getResponseOwner()); 
				} 	*/	
				auditObservationDao.flushSession();
				auditObservationDao.saveOrUpdate(auditObservationRespondReviewCapture);
			}
					logger.info("11 :: save remarks.."+ ((System.currentTimeMillis()-start)/1000));
			
			/************** Remarks End *********************/
			
			/************** To update Report Master table based on checklist update Start *********************/			
			if(rolesListInspector.contains(auditObservation.getRole())){
				start = System.currentTimeMillis();
				auditBookReportServiceV3.updateChecklistForReportTable(auditObservation.getLegalEntityCode(), 
						auditObservation.getMappingId(),
						auditObservation.getAuditId(), auditObservation.getAuditTypeCode(),
						auditObservation.getAuditGroupCode(), auditObservation.getAuditSubGroupCode(), 
						auditObservation.getActivityCode(), auditObservation.getProcessCode(),
						auditObservation.getFindingCode(), auditObservation.getComplianceCategory(), auditObservation.getReportLanguage(), 
						auditObservation.getNonCompliancePersistence(), auditObservation.getObservationCriticality());
				logger.info("12 :: save chkRepTab.."+ ((System.currentTimeMillis()-start)/1000));
				
				start = System.currentTimeMillis();
				auditBookReportServiceV3.updateRemarksForReportTable(auditObservation.getLegalEntityCode(), 
						auditObservation.getMappingId(),
						auditObservation.getAuditId(), auditObservation.getAuditTypeCode(),
						auditObservation.getAuditGroupCode(), auditObservation.getAuditSubGroupCode(), 
						auditObservation.getActivityCode(), auditObservation.getProcessCode(),
						auditObservation.getFindingCode(),auditObservation.getComplianceCategory(),
						auditObservation.getFindingRemarks(), auditObservation.getReportLanguage() );
				logger.info("13 :: save remarkForTab.."+ ((System.currentTimeMillis()-start)/1000));
				
					start = System.currentTimeMillis();
				//String pritFlag=auditObservation.getStandardStatementPrintFlag()==null?"Y":auditObservation.getStandardStatementPrintFlag();
				//if(pritFlag.equalsIgnoreCase(BankAuditConstant.YES)){
				//if(!auditObservation.getStandardStatementPrintFlag().equalsIgnoreCase(BankAuditConstant.NO)){
				if(!(BankAuditConstant.NO).equalsIgnoreCase(auditObservation.getStandardStatementPrintFlag())){
					auditBookReportServiceV3.updateStandardStatementForReportTable(auditObservation.getLegalEntityCode(), 
							auditObservation.getMappingId(),
							auditObservation.getAuditId(), auditObservation.getAuditTypeCode(),
							auditObservation.getAuditGroupCode(), auditObservation.getAuditSubGroupCode(), 
							auditObservation.getActivityCode(), auditObservation.getProcessCode(),
							auditObservation.getFindingCode(),auditObservation.getComplianceCategory(),
							auditObservation.getStandardStatement(), auditObservation.getStandardStatementHindi(), auditObservation.getReportLanguage());
				}else{
					auditBookReportServiceV3.updateStandardStatementForReportTable(auditObservation.getLegalEntityCode(), 
							auditObservation.getMappingId(),
							auditObservation.getAuditId(), auditObservation.getAuditTypeCode(),
							auditObservation.getAuditGroupCode(), auditObservation.getAuditSubGroupCode(), 
							auditObservation.getActivityCode(), auditObservation.getProcessCode(),
							auditObservation.getFindingCode(),auditObservation.getComplianceCategory(),
							"","", auditObservation.getReportLanguage());
				}			
				logger.info("14 :: Update StndStmnt.."+ ((System.currentTimeMillis()-start)/1000));
				
			}else if(rolesListCompliance.contains(auditObservation.getRole())){
				start = System.currentTimeMillis();
					auditBookReportServiceV3.updateBankRemarksForReportTable(auditObservation.getLegalEntityCode(), 
					auditObservation.getMappingId(),
					auditObservation.getAuditId(), auditObservation.getAuditTypeCode(),
					auditObservation.getAuditGroupCode(), auditObservation.getAuditSubGroupCode(), 
					auditObservation.getActivityCode(), auditObservation.getProcessCode(),
					auditObservation.getFindingCode(),auditObservation.getComplianceCategory(),
					auditObservation.getResponseRemarks(), auditObservation.getReportLanguage() );
				logger.info("14.2 :: Update BankRemarks.."+ ((System.currentTimeMillis()-start)/1000));
			}else if(rolesListReviewer.contains(auditObservation.getRole())){ 
					start = System.currentTimeMillis();
				String scrutinyReviewRemarks = auditObservation.getReviewRemarks()==null?" ":auditObservation.getReviewRemarks();
								
				auditBookReportServiceV3.updateScrutinyRemarksForReportTable(auditObservation.getLegalEntityCode(), 
					auditObservation.getMappingId(),
					auditObservation.getAuditId(), auditObservation.getAuditTypeCode(),
					auditObservation.getAuditGroupCode(), auditObservation.getAuditSubGroupCode(), 
					auditObservation.getActivityCode(), auditObservation.getProcessCode(),
					auditObservation.getFindingCode(),auditObservation.getComplianceCategory(),
					fcValue +":#@:"+ scrutinyReviewRemarks, auditObservation.getReportLanguage());
				logger.info("14.3 :: Update BankRemarks.."+ ((System.currentTimeMillis()-start)/1000));
				
				//update Compliance rating 
				auditObservationDao.updateComplinaceRating(auditObservation);
			}
			
			/************** To update Report Master table based on checklist update End *********************/		
		}
		
		/*
		start = System.currentTimeMillis();
	    if(auditObservationDto.getDuplicateDocIds()!=null){
			for (Integer  duplicateDocId : auditObservationDto.getDuplicateDocIds()) {
				auditObservationDao.deleteById(AuditDocumentDetails.class, duplicateDocId);
			}
		}
	    logger.info("15 :: del dup doc .."+ ((System.currentTimeMillis()-start)/1000));
	    
	    
		if(auditObservationDto.getDocumentUploadId()!=null){
			start = System.currentTimeMillis();
			auditDocumentDetailsTemp=(AuditDocumentDetailsTemp) auditObservationDao.get(AuditDocumentDetailsTemp.class, 
					auditObservationDto.getDocumentUploadId());
			AuditDocumentDetails auditDocumentDetails=null;
			logger.info("16 :: get doc .."+ ((System.currentTimeMillis()-start)/1000));
			
			start = System.currentTimeMillis();
			for (String url : auditDocumentDetailsTemp.getUrls().split(BankAuditConstant.DELIMITER_URL)) {
				auditDocumentDetails=new AuditDocumentDetails();
				auditDocumentDetails.setLegalEntityCode(auditObservationDto.getAuditObservations().get(0).getLegalEntityCode());
				auditDocumentDetails.setAuditTypeCode(auditObservationDto.getAuditObservations().get(0).getAuditTypeCode());
				auditDocumentDetails.setPlanId(auditObservationDto.getAuditObservations().get(0).getPlanId());
				auditDocumentDetails.setAuditId(auditObservationDto.getAuditObservations().get(0).getAuditId());
				auditDocumentDetails.setDocumentType(auditDocumentDetailsTemp.getRole()+"-G");
				auditDocumentDetails.setEntityStatus(auditObservationDto.getAuditObservations().get(0).getEntityStatus());
				auditDocumentDetails.setStatus("A");
				auditDocumentDetails.setMaker(auditObservationDto.getAuditObservations().get(0).getMaker());
	            auditDocumentDetails.setChecker(auditObservationDto.getAuditObservations().get(0).getChecker());
				auditDocumentDetails.setBusinessdateTimestamp(auditObservationDto.getAuditObservations().get(0).getBusinessdateTimestamp());
				auditDocumentDetails.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
				auditDocumentDetails.setMakerTimestamp(auditDocumentDetails.getBusinessdateTimestamp());
				auditDocumentDetails.setReferencePath(url);
				auditDocumentDetails.setObservationId(groupObservationId);
								
				auditObservationDao.save(auditDocumentDetails);
			}
			logger.info("17 :: save audit doc .."+ ((System.currentTimeMillis()-start)/1000));
			start = System.currentTimeMillis();
			auditObservationDao.delete(auditDocumentDetailsTemp);
			logger.info("18 :: delete audit doc .."+ ((System.currentTimeMillis()-start)/1000));
		}
		
		start = System.currentTimeMillis();
		AuditObservation auditObservation=auditObservations.get(0);
		if(auditObservation.getSubmissionStatus().equalsIgnoreCase("A")
				|| auditObservation.getReviewStatus().equalsIgnoreCase("A")
				|| auditObservation.getResponseStatus().equalsIgnoreCase("A")){
			AuditSchedule auditSchedule=getObservationCounts(auditObservation.getLegalEntityCode(), auditObservation.getAuditTypeCode(), auditObservation.getPlanId(), auditObservation.getAuditId());
			auditSchedule.setLegalEntityCode(auditObservation.getLegalEntityCode());
			auditSchedule.setAuditTypeCode(auditObservation.getAuditTypeCode());
			auditSchedule.setPlanId(auditObservation.getPlanId());
			auditSchedule.setAuditId(auditObservation.getAuditId());
			myAuditsService.updateAuditScheduleCounts(auditSchedule);
		}
		logger.info("19 :: update audit sch .."+ ((System.currentTimeMillis()-start)/1000));
		
		logger.info("Total obs update .."+ ((System.currentTimeMillis()-start0)/1000));
		*/
		
		return groupObservationId;
	}

	@Override
	public List<AuditObservation> getObservationByObservationGroupId(String observationGroupId,Integer legalEntityCode) {
		
		return auditObservationDao.getObservationByObservationGroupId( observationGroupId,legalEntityCode);
	}

	@Override
	public AuditSchedule getObservationCounts(Integer legalEntityCode, String auditTypeCode, String planId,
			String auditId) {
		
		return auditObservationDao.getObservationCounts( legalEntityCode,  auditTypeCode,  planId,
				 auditId);
	}

	/*@Override
	public Integer uploadDocument(String maker,String role,CommonsMultipartFile[] files,String fileName) throws Exception {


		AuditDocumentDetailsTemp auditDocumentDetailsTemp=new AuditDocumentDetailsTemp();
		
		auditDocumentDetailsTemp.setMakerTimestamp(new Timestamp(System.currentTimeMillis()));
		auditDocumentDetailsTemp.setMaker(maker);
		auditDocumentDetailsTemp.setRole(role);
		String referencePath="";
      for (CommonsMultipartFile commonsMultipartFile : files) {

    		String pattern = "yyyyMMddHHmmssSSS";
    		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
    		referencePath=referencePath+BankAuditConstant.DELIMITER_URL+BankAuditUtil.uploadMaterial(commonsMultipartFile, BankAuditConstant.DIR_DOC_UPLOAD, simpleDateFormat.format(new Date())+"_"+fileName);
  			
	}	
      referencePath=referencePath.substring(3);
      
      auditDocumentDetailsTemp.setUrls(referencePath);
      auditObservationDao.save(auditDocumentDetailsTemp);
      
      return auditDocumentDetailsTemp.getId();
		
	}*/

	/*@Override
	public List<AuditDocumentDetails> getAuditDocumentDetails(Integer legalEntityCode, String auditTypeCode,
			String planId, String auditId, String observationId, String documentType) {
		
		return auditObservationDao.getAuditDocumentDetails( legalEntityCode,  auditTypeCode,
				 planId,  auditId,  observationId,  documentType);
	}*/

	/*@Override
	public AuditDocumentDetails getAuditDocumentDetails(Integer id, Integer legalEntityCode, String auditTypeCode,
			String planId, String auditId, String observationId, String documentType) {
		
	   Map<String, Object> properties=new HashMap<>();
	   
	   properties.put("id", id);
	   properties.put("legalEntityCode", legalEntityCode);
	   properties.put("auditTypeCode", auditTypeCode);
	   properties.put("planId", planId);
	   properties.put("auditId", auditId);
	   properties.put("observationId", observationId);
	   properties.put("documentType", documentType);
		
		return (AuditDocumentDetails)auditObservationDao.getUniqueEntityByMatchingProperties(AuditDocumentDetails.class, properties);
	}*/

	@Override
	public AuditObservation getAuditObservation(Integer legalEntityCode, String auditTypeCode, String planId,
			String auditId, String groupObservationId, String observationId) {
		
		AuditObservation auditObservation= auditObservationDao.getAuditObservation( legalEntityCode,  auditTypeCode,  planId,
				 auditId,  groupObservationId,  observationId);
		
		
		auditObservation.setAuditObservationRespondReviewCaptures(getAuditObservationRespondReviewCaptureByObservation(legalEntityCode, auditTypeCode, planId, auditId, groupObservationId, observationId));
		return auditObservation;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<AuditObservationRespondReviewCapture> getAuditObservationRespondReviewCaptureByObservation(
			Integer legalEntityCode, String auditTypeCode, String planId, String auditId, String groupObservationId,
			String observationId) {
		return auditObservationDao.getAuditObservationRespondReviewCaptureByObservation(legalEntityCode,  auditTypeCode,  planId,  auditId,  groupObservationId,observationId);
	}

	@Override
	public Integer updateResponseObservation(AuditObservation auditObservation) {
		
        Integer respondReviewCaptureId=null;
		
		AuditDocumentDetailsTemp auditDocumentDetailsTemp=null;
		
		//Map<String,Object> properties=new HashMap<String, Object>();
        AuditObservation auditObservationStored=getAuditObservation(auditObservation.getLegalEntityCode(),
        		auditObservation.getAuditTypeCode(), auditObservation.getPlanId(),
        		auditObservation.getAuditId(),
        		auditObservation.getGroupObservationId(),
        		auditObservation.getObservationId());
        // save into the history table 
        if(auditObservationStored!=null){
        	auditObservationStored.setAuditTypeCode(auditObservation.getAuditTypeCode());
        	auditObservationDao.save(new AuditObservationHst(auditObservationStored));
        }
        
		// delete the old record 
		auditObservationDao.deleteById(auditObservation);
		
	
		

		auditObservation.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(auditObservation.getLegalEntityCode()));
		auditObservation.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
		if(auditObservation.getObservationId()==null){
			auditObservation.setObservationId(sequenceAppenderService.getAutoSequenceId());
		}
		auditObservationDao.flushSession();
		auditObservationDao.save(auditObservation);
		
		if(auditObservation.getAuditObservationRespondReviewCaptures()!=null){
			for (AuditObservationRespondReviewCapture auditObservationRespondReviewCapture: auditObservation.getAuditObservationRespondReviewCaptures()) {
				auditObservationRespondReviewCapture.setMakerTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(auditObservationRespondReviewCapture.getLegalEntityCode()));
				auditObservationDao.saveOrUpdate(auditObservationRespondReviewCapture);
				respondReviewCaptureId=auditObservationRespondReviewCapture.getId();
			}
		}
		
		if(auditObservation.getDuplicateDocIds()!=null){
						
						for (Integer  duplicateDocId : auditObservation.getDuplicateDocIds()) {
							auditObservationDao.deleteById(AuditDocumentDetails.class, duplicateDocId);
						}
						
					}
		
		if(auditObservation.getDocumentUploadId()!=null){
			auditDocumentDetailsTemp=(AuditDocumentDetailsTemp) auditObservationDao.get(AuditDocumentDetailsTemp.class, 
					auditObservation.getDocumentUploadId());
			
			
			for (String url : auditDocumentDetailsTemp.getUrls().split(BankAuditConstant.DELIMITER_URL)) {

				AuditDocumentDetails auditDocumentDetails=new AuditDocumentDetails();
				auditDocumentDetails.setLegalEntityCode(auditObservation.getLegalEntityCode());
				auditDocumentDetails.setAuditTypeCode(auditObservation.getAuditTypeCode());
				auditDocumentDetails.setPlanId(auditObservation.getPlanId());
				auditDocumentDetails.setAuditId(auditObservation.getAuditId());
				auditDocumentDetails.setDocumentType(auditDocumentDetailsTemp.getRole()+"-S");
				auditDocumentDetails.setEntityStatus(auditObservation.getEntityStatus());
				auditDocumentDetails.setStatus("A");
				auditDocumentDetails.setMaker(auditObservation.getMaker());
	            auditDocumentDetails.setChecker(auditObservation.getChecker());
				auditDocumentDetails.setBusinessdateTimestamp(auditObservation.getBusinessdateTimestamp());
				auditDocumentDetails.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
				auditDocumentDetails.setMakerTimestamp(auditDocumentDetails.getBusinessdateTimestamp());
				auditDocumentDetails.setReferencePath(url);
				auditDocumentDetails.setObservationId(auditObservation.getObservationId());
				auditObservationDao.save(auditDocumentDetails);
				
			}
			auditObservationDao.delete(auditDocumentDetailsTemp);
		}
		
		if( (auditObservation.getReviewStatus()!=null && auditObservation.getReviewStatus().equalsIgnoreCase("A"))
				||( auditObservation.getResponseStatus()!=null &&  auditObservation.getResponseStatus().equalsIgnoreCase("A"))){
			AuditSchedule auditSchedule=getObservationCounts(auditObservation.getLegalEntityCode(), auditObservation.getAuditTypeCode(), auditObservation.getPlanId(), auditObservation.getAuditId());
			auditSchedule.setLegalEntityCode(auditObservation.getLegalEntityCode());
			auditSchedule.setAuditTypeCode(auditObservation.getAuditTypeCode());
			auditSchedule.setPlanId(auditObservation.getPlanId());
			auditSchedule.setAuditId(auditObservation.getAuditId());
			myAuditsService.updateAuditScheduleCounts(auditSchedule);
		}
		
	return respondReviewCaptureId;
		
	}
	
	@Override
	public Map<String, String> validateAccObsMapping(Integer legalEntityCode,String auditTypeCode,String planId,String auditId,String custId,String accountNo,String captureType,String mappingId,String type) {
		
	   Map<String, String> grpObsId_ObsId=auditObservationDao.validateAccObsMapping(legalEntityCode,auditTypeCode,planId,auditId, custId,accountNo,captureType, mappingId, type);
	   return grpObsId_ObsId;
	}
	
	//******************** NABARD RISK Related Services started here *********************************//
	
	@Override
	public List<AuditObservation> getAllPossibleRisk(int legalEntityCode, String auditTypeCode, String auditId, String planId, String userId) { 
		logger.info("Inside servcImpl  getAllPossibleRisk "); 
		List<AuditObservation> AuditObservationLst =null;
		boolean isPreviousAuditExist = false;
		try {
			String unitId=null;
			isPreviousAuditExist = myAuditsService.isPreviousAuditExist(legalEntityCode, unitId, auditTypeCode, auditId);
			logger.info("isPreviousAuditExist .."+isPreviousAuditExist);
			if(isPreviousAuditExist)
				AuditObservationLst = auditObservationDao.getAllPossibleRiskFromPrevAssessment(legalEntityCode, auditTypeCode, auditId, planId, userId);
			else AuditObservationLst = auditObservationDao.getAllPossibleRiskFromMapping(legalEntityCode, auditTypeCode, auditId, planId, userId);
		}catch(Exception e) {
			e.printStackTrace();
		}
		return AuditObservationLst;
	}
	
	// Method only to insert Observation data while Initiating
	@Override
	public void insertBulkObservationCapture(List<AuditObservation> auditObservationLst, int legalEntityCode, String auditTypeCode, String auditId, String planId){
		logger.info("Inside AuditObsSrvcImpl --> insertBulkObservationCapture() :: "+ legalEntityCode+" :: "+ auditTypeCode +" :: "+auditId); 
		try {
			logger.info("auditObservationLst .. "+ auditObservationLst);
			String obsId=null,  maker=null;
			for (AuditObservation auditObservation : auditObservationLst) {
				obsId=sequenceAppenderService.getAutoSequenceId();
				
				auditObservation.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(auditObservation.getLegalEntityCode()));
				auditObservation.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
				auditObservation.setMakerTimestamp(auditObservation.getBusinessdateTimestamp());
				
				auditObservation.setGroupObservationId(obsId);
				auditObservation.setObservationId(obsId);
				auditObservation.setEntityStatus(BankAuditConstant.STATUS_ACTIVE);  // added to handle the Doc upload issue
				auditObservationDao.flushSession();
				auditObservationDao.save(auditObservation);
			}
			auditObservationDao.flushSession();
			String updateSts=updatingOthersToNA( legalEntityCode,  auditTypeCode,  auditId);
			myAuditsService.updateAuditStatusDetailAfterInitiate(legalEntityCode, auditTypeCode, planId, auditId, auditObservationLst.size());
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}		
	}
	
	@Override
	public void insertBulkRiskCapture(List<AuditObservation> auditObservationLst){
		logger.info("Inside AuditObsSrvcImpl --> insertBulkRiskCapture("); 
		try {
			logger.info("auditObservationLst .. "+ auditObservationLst);
			String prevObsId=null; String prevAuditId=null;
			String obsId=null; String auditId=null;
			Integer LE =null;String maker=null;
			List<RiskControlDetails> lstRiskCntDtls = null;
			List<ControlGapDetails> lstCntGpDtls = null;
			for (AuditObservation auditObservation : auditObservationLst) {
				prevObsId= auditObservation.getTmpObservationId();  
				prevAuditId= auditObservation.getPrevAuditId(); 
				maker=auditObservation.getMaker();
				LE=auditObservation.getLegalEntityCode();
				obsId=sequenceAppenderService.getAutoSequenceId();
				auditId=auditObservation.getAuditId();
				
				auditObservation.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(auditObservation.getLegalEntityCode()));
				auditObservation.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
				auditObservation.setMakerTimestamp(auditObservation.getBusinessdateTimestamp());
				
				auditObservation.setGroupObservationId(obsId);
				auditObservation.setObservationId(obsId);
				auditObservation.setEntityStatus(BankAuditConstant.STATUS_ACTIVE);  // added to handle the Doc upload issue
				auditObservationDao.flushSession();
				auditObservationDao.save(auditObservation);
				
				logger.info("prevObsId .."+prevObsId +" prevAuditId .."+prevAuditId+" obsId .."+obsId + " auditId.. "+auditId);
				if(prevAuditId != null && prevObsId != null) {
					lstRiskCntDtls =riskControlDetailsDao.getRiskControlDetails(LE, prevAuditId, prevObsId, "A");
					Integer riskIdCnt=1;Integer cntGpIdCnt=1;
					for (RiskControlDetails riskControlDetails : lstRiskCntDtls) {
						riskControlDetails.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(auditObservation.getLegalEntityCode()));
						riskControlDetails.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
						riskControlDetails.setMakerTimestamp(auditObservation.getBusinessdateTimestamp());
						riskControlDetails.setMaker(maker);
						riskControlDetails.setAuditId(auditId);
						riskControlDetails.setObservationId(obsId);
						try {
							int id=Integer.parseInt(riskControlDetails.getObservationId());
							id= id * 100 +riskIdCnt;
							riskControlDetails.setId(id);
						}catch(Exception e) {
							riskControlDetails.setId(Integer.parseInt(sequenceAppenderService.getAutoSequenceId()));
						}
						riskControlDetails.setStatus("U");
						riskControlDetailsDao.flushSession();
						riskControlDetailsDao.save(riskControlDetails);
						riskIdCnt++;
					}
					lstCntGpDtls =controlGapDetailsDao.getControlGapDetails(LE, prevAuditId, prevObsId, "A");
					for (ControlGapDetails controlGapDetails : lstCntGpDtls) {
						controlGapDetails.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(auditObservation.getLegalEntityCode()));
						controlGapDetails.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
						controlGapDetails.setMakerTimestamp(auditObservation.getBusinessdateTimestamp());
						controlGapDetails.setMaker(maker);
						controlGapDetails.setAuditId(auditId);
						controlGapDetails.setObservationId(obsId);
						try {
							int id=Integer.parseInt(controlGapDetails.getObservationId());
							id= id * 100 +cntGpIdCnt;
							controlGapDetails.setId(id);
						}catch(Exception e) {
							controlGapDetails.setId(Integer.parseInt(sequenceAppenderService.getAutoSequenceId()));
						}
						controlGapDetails.setStatus("U");
						controlGapDetailsDao.flushSession();
						controlGapDetailsDao.save(controlGapDetails);
						cntGpIdCnt++;
					}
				}
			}
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
		
	}
	
	@Override
	public AuditObservation getRiskDtlsByRiskId(Integer legalEntityCode, String auditId, String observationId, String userId, String status) {
		
		AuditObservation auditObservation = auditObservationDao.getRiskDtlsByRiskId( legalEntityCode,auditId,observationId, userId, status);
		try {
		if(auditObservation!=null ){ 
			auditObservation.setRiskControlDetailsLst(riskControlDetailsService.getRiskControlDetails(legalEntityCode, auditId, observationId, status));
			auditObservation.setControlGapDetailsLst(controlGapDetailsService.getControlGapDetails(legalEntityCode, auditId, observationId, status));
			auditObservation.setRecommendationDetailsLst(recommendationDetailsService.getRecommendationDetails(legalEntityCode, auditId, observationId, status));
			auditObservation.setTaskDetailsLst(taskDetailsService.getTaskDetails(legalEntityCode, auditId, observationId, status));
		}
		}catch(Exception e){
			e.printStackTrace(System.out);
		}
		return auditObservation;
	}
	
	
	@SuppressWarnings("unchecked")
	@Override
	public void updateRiskDetails(AuditObservationRiskDto auditObservationRiskDto) {

		logger.info("Inside updateRiskDetails of AuditObservationServiceImpl .. .."+auditObservationRiskDto.getStatus()+ " :: " + auditObservationRiskDto);
		try {
			AuditObservation auditObservation = auditObservationRiskDto.getAuditObservation();

			String observationId = auditObservationRiskDto.getAuditObservation().getObservationId();

			Map<String, Object> properties = new HashMap<String, Object>();
			properties.put("observationId", observationId);
			List<AuditObservation> auditObservationsStored = auditObservationDao
					.getEntitiesByMatchingProperties(AuditObservation.class, properties);

			if (auditObservationsStored != null) {
				for (AuditObservation auditObservationTmp : auditObservationsStored) {
					auditObservationDao.save(new AuditObservationHst(auditObservationTmp));
				}
			}

			auditObservationDao.deleteObservationById(observationId);

			// for (AuditObservation auditObservation : auditObservations) {
			if (auditObservation != null) {
				auditObservation.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(auditObservation.getLegalEntityCode()));
				auditObservation.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
				if(auditObservation.getFindingCriticality() !=null) {
					auditObservation.setFindingCriticality(auditObservation.getFindingCriticality().split("-")[0]);
				}
				if(auditObservationRiskDto.getStatus().contains("A")) {
					auditObservation.setChecker(auditObservationRiskDto.getUserId());
					auditObservation.setCheckerTimestamp(auditObservation.getBusinessdateTimestamp());
				}else {
					auditObservation.setMaker(auditObservationRiskDto.getUserId());
					auditObservation.setCheckerTimestamp(auditObservation.getBusinessdateTimestamp());
				}
				
				auditObservationDao.flushSession();
				auditObservationDao.save(auditObservation);

				//if(auditObservationRiskDto.getStatus() != null && !(auditObservationRiskDto.getStatus().equalsIgnoreCase("OA") ||
				if(auditObservationRiskDto.getStatus() != null && !(auditObservationRiskDto.getStatus().equalsIgnoreCase("OR") ||
						auditObservationRiskDto.getStatus().equalsIgnoreCase("RA") || auditObservationRiskDto.getStatus().equalsIgnoreCase("WA"))){  // OA- SubmissionAuth, RA- RespondAuth, WA-ReviewAuth
					logger.info("for Updating the records .....");
					if (auditObservationRiskDto.getStatus() != null && auditObservationRiskDto.getStatus().substring(0,1).contains("O") 
							&& auditObservation.getRiskControlDetailsLst() != null ) {
						//This block is for RiskControl Details 
						if(auditObservationRiskDto.getStatus().equalsIgnoreCase("OA")) {
							Map<String, Object> riskProperties = new HashMap<String, Object>();
							riskProperties.put("observationId", observationId);
							List<RiskControlDetails> riskControlDetailsStored = riskControlDetailsDao
									.getEntitiesByMatchingProperties(RiskControlDetails.class, riskProperties);
							for (RiskControlDetails riskControlDetailsTmp : riskControlDetailsStored) {
								riskControlDetailsDao.save(new RiskControlDetailsHst(riskControlDetailsTmp));
							}
						}
						riskControlDetailsDao.deleteRiskControlDetailsByObservationId(observationId);
	
						logger.info("obsId .." + auditObservation.getObservationId());
						for (RiskControlDetails riskControlDetails : auditObservation.getRiskControlDetailsLst()) {
	
							riskControlDetails.setMaker(auditObservation.getMaker());
							riskControlDetails.setChecker(auditObservation.getChecker());
							riskControlDetails.setBusinessdateTimestamp(auditObservation.getBusinessdateTimestamp());
							riskControlDetails.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
							riskControlDetails.setMakerTimestamp(riskControlDetails.getBusinessdateTimestamp());
							if (riskControlDetails.getStatus() != null) {
								if(auditObservationRiskDto.getStatus().equalsIgnoreCase("OA")) {
									if ("D".equalsIgnoreCase(riskControlDetails.getStatus())) {
										riskControlDetailsDao.deleteRiskControlDetailsById(riskControlDetails.getId());
									}else {
										riskControlDetails.setStatus("A");
										riskControlDetailsDao.flushSession();
										riskControlDetailsDao.save(riskControlDetails);
									}
								} else {
									if ("N".equalsIgnoreCase(riskControlDetails.getStatus())) {
										riskControlDetails.setId(Integer.parseInt(sequenceAppenderService.getAutoSequenceId()));
									}riskControlDetailsDao.flushSession();
									riskControlDetailsDao.save(riskControlDetails);
								}
							}
						}
					} else if (auditObservationRiskDto.getStatus() != null && auditObservationRiskDto.getStatus().substring(0,1).contains("R") 
							&& auditObservation.getControlGapDetailsLst() != null ) {
						//This block is for Control Gap Details 
						Map<String, Object> controlGapProperties = new HashMap<String, Object>();
						controlGapProperties.put("observationId", observationId);
						List<ControlGapDetails> controlGapDetailsStored = controlGapDetailsDao.getEntitiesByMatchingProperties(ControlGapDetails.class, controlGapProperties);
						for (ControlGapDetails controlGapDetailsTmp : controlGapDetailsStored) {
							controlGapDetailsDao.save(new ControlGapDetailsHst(controlGapDetailsTmp));
						}
						controlGapDetailsDao.deleteControlGapDetailsByObservationId(observationId);
	
						logger.info("obsId .." + auditObservation.getObservationId());
						for (ControlGapDetails controlGapDetails : auditObservation.getControlGapDetailsLst()) {
	
							controlGapDetails.setBusinessdateTimestamp(auditObservation.getBusinessdateTimestamp());
							controlGapDetails.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
							controlGapDetails.setMakerTimestamp(controlGapDetails.getBusinessdateTimestamp());
							if (controlGapDetails.getStatus() != null) {
								if ("D".equalsIgnoreCase(controlGapDetails.getStatus())) {
									controlGapDetailsDao.deleteControlGapDetailsById(controlGapDetails.getId());
								} else if ("U".equalsIgnoreCase(controlGapDetails.getStatus())) {
									controlGapDetailsDao.flushSession();
									controlGapDetailsDao.save(controlGapDetails);
								} else if ("N".equalsIgnoreCase(controlGapDetails.getStatus())) {
									controlGapDetails.setId(Integer.parseInt(sequenceAppenderService.getAutoSequenceId()));
									controlGapDetails.setStatus("U");
									controlGapDetailsDao.flushSession();
									controlGapDetailsDao.save(controlGapDetails);
								}
							}
						}
					} else if (auditObservationRiskDto.getStatus() != null && auditObservationRiskDto.getStatus().substring(0,1).contains("W") ) {
						if( auditObservation.getRecommendationDetailsLst() != null){
							Map<String, Object> recomProperties = new HashMap<String, Object>();
							properties.put("observationId", observationId);
							List<RecommendationDetails> recommendationDetailsStored = riskControlDetailsDao.getEntitiesByMatchingProperties(RecommendationDetails.class, properties);
							for (RecommendationDetails recommendationDetailsTmp : recommendationDetailsStored) {
								recommendationDetailsDao.save(new RecommendationDetailsHst(recommendationDetailsTmp));
							}
							recommendationDetailsDao.deleteRecommendationDetailsByObservationId(observationId);
		
							logger.info("obsId .." + auditObservation.getObservationId());
							for (RecommendationDetails recommendationDetails : auditObservation.getRecommendationDetailsLst()) {
		
								recommendationDetails.setBusinessdateTimestamp(auditObservation.getBusinessdateTimestamp());
								recommendationDetails.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
								if (recommendationDetails.getStatus() != null) {
									if ("D".equalsIgnoreCase(recommendationDetails.getStatus())) {
										recommendationDetailsDao.deleteRecommendationDetailsById(recommendationDetails.getId());
									} else if ("U".equalsIgnoreCase(recommendationDetails.getStatus())) {
										recommendationDetailsDao.flushSession();
										recommendationDetailsDao.save(recommendationDetails);
									} else if ("N".equalsIgnoreCase(recommendationDetails.getStatus())) {
										recommendationDetails.setId(Integer.parseInt(sequenceAppenderService.getAutoSequenceId()));
										recommendationDetails.setStatus("U");
										recommendationDetailsDao.flushSession();
										recommendationDetailsDao.save(recommendationDetails);
									}
								}
							}
						}
					}
					logger.info(" TaskDetailsLst() .. "+auditObservation.getTaskDetailsLst());
						if( auditObservation.getTaskDetailsLst() != null && auditObservation.getTaskDetailsLst().size() > 0) {
							logger.info(" TaskDetailsLst() .. "+auditObservation.getTaskDetailsLst().size());
							Map<String, Object> taskProperties = new HashMap<String, Object>();
							properties.put("observationId", observationId);
							List<TaskDetails> taskDetailsStored = riskControlDetailsDao.getEntitiesByMatchingProperties(TaskDetails.class, taskProperties);
							logger.info("Task records ........ "+taskDetailsStored.size());
							for (TaskDetails taskDetailsTmp : taskDetailsStored) {
								taskDetailsDao.save(new TaskDetailsHst(taskDetailsTmp));
							}
							taskDetailsDao.deleteTaskDetailsByObservationId(observationId);
		
							logger.info("obsId .." + auditObservation.getObservationId());
							for (TaskDetails taskDetails : auditObservation.getTaskDetailsLst()) {
								taskDetails.setBusinessdateTimestamp(auditObservation.getBusinessdateTimestamp());
								taskDetails.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
								taskDetails.setMakerTimestamp(taskDetails.getBusinessdateTimestamp());
								taskDetails.setTaskStatus("Open");
								if (taskDetails.getStatus() != null) {
									if ("D".equalsIgnoreCase(taskDetails.getStatus())) {
										taskDetailsDao.deleteTaskDetailsById(taskDetails.getId());
									} else if ("U".equalsIgnoreCase(taskDetails.getStatus())) {
										taskDetailsDao.flushSession();
										taskDetailsDao.save(taskDetails);
									} else if ("N".equalsIgnoreCase(taskDetails.getStatus())) {
										taskDetails.setId(Integer.parseInt(sequenceAppenderService.getAutoSequenceId()));
										taskDetails.setStatus("U");
										taskDetailsDao.flushSession();
										taskDetailsDao.save(taskDetails);
									}
								}
							}
						}
				
				}
				
				/*********************** Code to Handle Auto Auth for AUDIT Capture **********************************/
				if (auditObservationRiskDto.getStatus() != null && auditObservationRiskDto.getStatus().equalsIgnoreCase("RA") 
						&& auditObservation.getControlGapDetailsLst() != null ) {
					//This block is for Control Gap Details 
					Map<String, Object> controlGapProperties = new HashMap<String, Object>();
					controlGapProperties.put("observationId", observationId);
					List<ControlGapDetails> controlGapDetailsStored = controlGapDetailsDao.getEntitiesByMatchingProperties(ControlGapDetails.class, controlGapProperties);
					for (ControlGapDetails controlGapDetailsTmp : controlGapDetailsStored) {
						controlGapDetailsDao.save(new ControlGapDetailsHst(controlGapDetailsTmp));
					}
					controlGapDetailsDao.deleteControlGapDetailsByObservationId(observationId);

					logger.info("obsId .." + auditObservation.getObservationId());
					for (ControlGapDetails controlGapDetails : auditObservation.getControlGapDetailsLst()) {
						controlGapDetails.setChecker(auditObservationRiskDto.getUserId());
						controlGapDetails.setBusinessdateTimestamp(auditObservation.getBusinessdateTimestamp());
						controlGapDetails.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
						controlGapDetails.setMakerTimestamp(controlGapDetails.getBusinessdateTimestamp());
						controlGapDetails.setCheckerTimestamp(controlGapDetails.getBusinessdateTimestamp());
						if (controlGapDetails.getStatus() != null) {
							if ("D".equalsIgnoreCase(controlGapDetails.getStatus())) {
								controlGapDetailsDao.deleteControlGapDetailsById(controlGapDetails.getId());
							} else if ("U".equalsIgnoreCase(controlGapDetails.getStatus())) {
								controlGapDetailsDao.flushSession();
								controlGapDetailsDao.save(controlGapDetails);
							} else if ("N".equalsIgnoreCase(controlGapDetails.getStatus())) {
								controlGapDetails.setId(Integer.parseInt(sequenceAppenderService.getAutoSequenceId()));
								controlGapDetailsDao.flushSession();
								controlGapDetailsDao.save(controlGapDetails);
							}
						}
					}
				}
				/************************** Auto AUTH,  Code End Here *********************************/
				
				/*********************** Code to make Status of TASK as A while Authorizing **********************************/
				if (auditObservationRiskDto.getStatus() != null && auditObservationRiskDto.getStatus().equalsIgnoreCase("WA") 
						&& auditObservation.getTaskDetailsLst() != null ) {
					for (TaskDetails taskDetails : auditObservation.getTaskDetailsLst()) {
						taskDetails.setTaskStatus("Open");
						taskDetails.setStatus("A");
						taskDetailsDao.flushSession();
						taskDetailsDao.saveOrUpdate(taskDetails);
					}
				}
				/************************** Auto AUTH,  Code End Here *********************************/
				
				/*if (auditObservation.getSubmissionStatus().equalsIgnoreCase("A")) {
				AuditSchedule auditSchedule = getObservationCounts(auditObservation.getLegalEntityCode(),
						auditObservation.getAuditTypeCode(), auditObservation.getPlanId(),
						auditObservation.getAuditId());
				auditSchedule.setLegalEntityCode(auditObservation.getLegalEntityCode());
				auditSchedule.setAuditTypeCode(auditObservation.getAuditTypeCode());
				auditSchedule.setPlanId(auditObservation.getPlanId());
				auditSchedule.setAuditId(auditObservation.getAuditId());
				myAuditsService.updateAuditScheduleCounts(auditSchedule);
			}*/
				
			}
		} catch (Exception e) {
			e.printStackTrace(System.out);
		}
	}
	
	//******************** BaaSDOS Related Services started here *********************************//
	
		@Override
		public List<AuditObservation> getAllPossibleMapping(int legalEntityCode, String auditTypeCode, String auditId, String planId, String userId) { 
			logger.info("Inside servcImpl  getAllPossibleMapping "); 
			List<AuditObservation> AuditObservationLst =null;
			boolean isPreviousAuditExist = false;
			try {
				String unitId=null;
				//isPreviousAuditExist = myAuditsService.isPreviousAuditExist(legalEntityCode, unitId, auditTypeCode, auditId);
				logger.info("isPreviousAuditExist .."+isPreviousAuditExist);
				if(isPreviousAuditExist)
					AuditObservationLst = auditObservationDao.getAllPossibleRiskFromPrevAssessment(legalEntityCode, auditTypeCode, auditId, planId, userId);
				else AuditObservationLst = auditObservationDao.getAllPossibleCheckListFromMapping(legalEntityCode, auditTypeCode, auditId, planId, userId);
			}catch(Exception e) {
				e.printStackTrace();
			}
			return AuditObservationLst;
		}
		
		@Override
		public  AuditObservation getInspectionObservation(Integer legalEntityCode,String auditId, String auditTypeCode, String groupObservationId, String observationId){		 	
			return auditObservationDao.getInspectionObservation(legalEntityCode,auditId, auditTypeCode, groupObservationId, observationId);
		}
		
		@Override
		public List<AuditObservationReportReviewCapture> getObservationReportReviewCaptureRemark(String legalEntityCode, String observationId ){
			
			return auditObservationDao.getObservationReportReviewCaptureRemark(legalEntityCode, observationId);
		}
		
		
		@SuppressWarnings("unchecked")
		@Override
		public String updateIndividualObservation(AuditObservationDto auditObservationDto) {
			
			AuditDocumentDetailsTemp auditDocumentDetailsTemp=null;
			List<AuditObservation> auditObservations=auditObservationDto.getAuditObservations();
			
			String groupObservationId=auditObservationDto.getGroupObservationId();
			
			Map<String,Object> properties=new HashMap<String, Object>();
			properties.put("groupObservationId", groupObservationId);
			AuditObservation auditObservationsStored=(AuditObservation)auditObservationDao.getUniqueEntityByMatchingProperties(AuditObservation.class, properties);
	        if(auditObservationsStored!=null) 
	        	auditObservationDao.save(new AuditObservationHst(auditObservationsStored));	
	            
	        for (AuditObservation auditObservation : auditObservations) {
				auditObservation.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(auditObservation.getLegalEntityCode()));
				auditObservation.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
				if(auditObservation.getObservationId()==null){
					auditObservation.setObservationId(sequenceAppenderService.getAutoSequenceId());
				}
				auditObservation.setGroupObservationId(groupObservationId);
				if(!BankAuditUtil.isEmptyString(auditObservation.getReviewNote())
						&& !BankAuditUtil.isEmptyString(auditObservation.getReviewNoteMaker())){
					auditObservation.setReviewNoteMakerTimestamp(new Timestamp(System.currentTimeMillis()).toString());
				}
				auditObservationDao.flushSession();
				auditObservationDao.saveOrUpdate(auditObservation);
				
				//Not maintaining remarks 
				//Call the service to save/update data into audit_observation_report_review_capture_wrk	 
				/*AuditObservationReportReviewCaptureWrk auditObservationReportReviewCaptureWrk = new AuditObservationReportReviewCaptureWrk();				
				auditObservationReportReviewCaptureWrk.setAuditId(auditObservation.getAuditId());
				auditObservationReportReviewCaptureWrk.setAuditTypeCode(auditObservation.getAuditTypeCode());
				auditObservationReportReviewCaptureWrk.setCaptureType(auditObservation.getCaptureType());
				auditObservationReportReviewCaptureWrk.setComment(auditObservation.getFindingRemarks());
				auditObservationReportReviewCaptureWrk.setGroupObservationId(auditObservation.getGroupObservationId());			 
				//auditObservationReportReviewCaptureWrk.setId(id);			
				auditObservationReportReviewCaptureWrk.setLegalEntityCode(auditObservation.getLegalEntityCode());
				auditObservationReportReviewCaptureWrk.setMaker(auditObservation.getMaker());
				auditObservationReportReviewCaptureWrk.setMakerTimestamp(auditObservation.getMakerTimestamp());
				auditObservationReportReviewCaptureWrk.setObservationId(auditObservation.getObservationId());
				auditObservationReportReviewCaptureWrk.setPlanId(auditObservation.getPlanId()); 
				
				auditObservationDao.deleteAuditObservationReportReviewCaptureWrk(auditObservationReportReviewCaptureWrk);
				auditObservationDao.save(auditObservationReportReviewCaptureWrk);*/	
				
				/********Code for notes	************/			
				if(!BankAuditUtil.isEmptyString(auditObservation.getObservationNote())
						|| !BankAuditUtil.isEmptyString(auditObservation.getReviewNote())
						|| !BankAuditUtil.isEmptyString(auditObservation.getResponseNote()) ){
					
					Boolean isSameUser = auditObservationDao.checkIfLatestNoteIsGivenBySameUser(auditObservation);		
					AuditObservationReportReviewCapture auditObservationReportReviewCapture = new AuditObservationReportReviewCapture();			
					if(isSameUser){
						auditObservationReportReviewCapture = auditObservationDao.getAuditObservationReportReviewCaptureLatest(auditObservation);
						if(auditObservationReportReviewCapture==null ||( auditObservationReportReviewCapture.getId()==null
								|| auditObservationReportReviewCapture.getId()<=0)){
							auditObservationReportReviewCapture = new AuditObservationReportReviewCapture();		
						}
					}						
					
					auditObservationReportReviewCapture.setLegalEntityCode(auditObservation.getLegalEntityCode());
					auditObservationReportReviewCapture.setPlanId(auditObservation.getPlanId()); 			 			
					auditObservationReportReviewCapture.setAuditTypeCode(auditObservation.getAuditTypeCode());
					auditObservationReportReviewCapture.setAuditId(auditObservation.getAuditId());
					auditObservationReportReviewCapture.setObservationId(auditObservation.getObservationId());
					auditObservationReportReviewCapture.setGroupObservationId(auditObservation.getGroupObservationId());		
								
					auditObservationReportReviewCapture.setMakerTimestamp(new Timestamp(System.currentTimeMillis()));				 					
					auditObservationReportReviewCapture.setCaptureType(auditObservation.getRole());	
					
					if( !BankAuditUtil.isEmptyString(auditObservation.getObservationNote())
							&& !BankAuditUtil.isEmptyString(auditObservation.getObservationNoteMaker()) ){
						auditObservationReportReviewCapture.setComment(auditObservation.getObservationNote());
						auditObservationReportReviewCapture.setMaker(auditObservation.getObservationNoteMaker());				
					}
					else if(!BankAuditUtil.isEmptyString(auditObservation.getReviewNote())
							&& !BankAuditUtil.isEmptyString(auditObservation.getReviewNoteMaker())){
						auditObservationReportReviewCapture.setComment(auditObservation.getReviewNote());
						auditObservationReportReviewCapture.setMaker(auditObservation.getReviewNoteMaker()); 
					}
					else if(!BankAuditUtil.isEmptyString(auditObservation.getResponseNote())
							&& !BankAuditUtil.isEmptyString(auditObservation.getResponseNoteMaker()) ){
						auditObservationReportReviewCapture.setComment(auditObservation.getResponseNote());
						auditObservationReportReviewCapture.setMaker(auditObservation.getResponseNoteMaker());				
					}				
					
					auditObservationDao.saveOrUpdate(auditObservationReportReviewCapture);
				}
				
			}
			
		    return groupObservationId;
		}
		
		/*@Override
		public Map<String, Integer>  uploadIndividualObservationDocument( AuditDocumentDetails auditDocumentDetails, CommonsMultipartFile[] files,String fileName)  {
			
			Map<String , Integer> uplodedIds = new HashMap<String , Integer>();				
			auditDocumentDetails.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(auditDocumentDetails.getLegalEntityCode()));
			 
			for (CommonsMultipartFile commonsMultipartFile : files) {
				AuditDocumentDetails auditDocumentDetailsToSave = new AuditDocumentDetails(); 
				Integer uploadId=0;
				try{ 
					BeanUtils.copyProperties(auditDocumentDetailsToSave, auditDocumentDetails); 
					String pattern = "yyyyMMddHHmmssSSS";
					SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
					//String referencePath = BankAuditConstant.DELIMITER_URL+BankAuditUtil.uploadMaterial(commonsMultipartFile, BankAuditConstant.DIR_DOC_UPLOAD, simpleDateFormat.format(new Date())+"_"+fileName);
					//referencePath=referencePath.substring(3);'
					String referencePath =  BankAuditUtil.uploadMaterial(commonsMultipartFile, BankAuditConstant.DIR_DOC_UPLOAD, simpleDateFormat.format(new Date())+"_"+fileName);
					auditDocumentDetailsToSave.setReferencePath(referencePath); 
					auditDocumentDetailsToSave.setFileName(commonsMultipartFile.getOriginalFilename());
					auditObservationDao.save(auditDocumentDetailsToSave);
					uploadId = auditDocumentDetailsToSave.getId();
				}catch (Exception e) {
					logger.error("Error .." + e.getMessage()+" :: "+e.getCause());				 
				}
				uplodedIds.put(commonsMultipartFile.getOriginalFilename(), uploadId);				
			}				  
			
			return uplodedIds;
		}*/
		
		/*public String deleteIndividualObservationDocument(Integer documentId){
			
			return 	auditObservationDao.deleteIndividualObservationDocument(documentId);
		 
		}*/
		
		/*@Override
		public String deleteAllObservationDocument(Integer legalEntityCode, String auditTypeCode,
			String planId, String auditId, String observationId, String documentType){		 			
				return 	auditObservationDao.deleteAllObservationDocument(legalEntityCode, auditTypeCode, planId, auditId, observationId, documentType);				 
		}*/
	//********************  END HERE *********************************//
		
		/**************Notes related Service **************/
		@Override
		public List<AuditObservationReportReviewCapture> getObservationReportReviewCaptureNotes(Integer legalEntityCode, String observationId, String role){
			return auditObservationDao.getObservationReportReviewCaptureNotes(legalEntityCode, observationId, role);
		}
		
		@Override
		public String submitObservationNotes(Integer legalEntityCode, String auditTypeCode,String auditId, String planId,  String role ){
			return auditObservationDao.submitObservationNotes(legalEntityCode, auditTypeCode, auditId, planId, role);
		}
		
		/**************Remarks related Service -Compliance Scrutiny **************/
		@Override
		public List<AuditObservationRespondReviewCapture> getAuditObservationRespondReviewCapture(Integer legalEntityCode, 
				String auditTypeCode,String auditId, String planId, String observationId, String role){ 
			return auditObservationDao.getAuditObservationRespondReviewCapture(legalEntityCode, auditTypeCode, auditId, planId, observationId, role);
		}
		
		//@SuppressWarnings("unchecked")
		@Override
		public AuditObservation updateObservationSpecificField(AuditObservation auditObservation, String fieldToUpdate) {
			return auditObservationDao.updateObservationSpecificField(auditObservation, fieldToUpdate);
		}
		
		//@SuppressWarnings("unchecked")
		@Override
		public int getCountRespondRejectedRecords(Integer legalEntityCode, String auditId) {
			return auditObservationDao.getCountRespondRejectedRecords(legalEntityCode, auditId);
		}
		
		// Method to get Compliance behavior (Non compliance Persistence or not)
		@Override
		public String getNonComplianceBehavior(Integer legalEntityCode, String auditId, String auditTypeCode, String unitId, String observationId, String mappingId){
			return auditObservationDao.getNonComplianceBehavior(legalEntityCode, auditId, auditTypeCode, unitId, observationId, mappingId);
		}
		
		// Method to Update the Compliance category for "Others", of Cheklists/Observations during Initiation
		@Override
		public String updatingOthersToNA(Integer legalEntityCode, String auditTypeCode,String auditId){
			logger.info("Inside updatingOthersToNA  .. "+ legalEntityCode +" :: "+auditTypeCode+" :: "+auditId);
			List<GeneralParameter> genParam=generalParameterDao.getGeneralParameter(legalEntityCode, null, null, BankAuditConstant.OBSERVATION_UPDATE, BankAuditConstant.OTHERS_COMPLIANCE_CATEGORY, null, null); // legalEntityCode, modCode, language, key1, key2, value, maker
			String othersUpdateStatus=null;
			if(!genParam.isEmpty()) {
				othersUpdateStatus=genParam.get(0).getValue();
				logger.info("othersUpdateStatus inside .."+othersUpdateStatus);
				if((BankAuditConstant.OBSERVATION_UPDATE_YES).equalsIgnoreCase(othersUpdateStatus)) {
					othersUpdateStatus=auditObservationDao.updatingOthersToNA(legalEntityCode, auditTypeCode, auditId);
				}else othersUpdateStatus="OTHERS_COMPLIANCE_CATEGORY Parameter defined as No.";
			}else othersUpdateStatus="OTHERS_COMPLIANCE_CATEGORY Parameter not defined.";
			logger.info("othersUpdateStatus .."+othersUpdateStatus);
			return othersUpdateStatus;
		}
		
		@Override
		public List<NonCompliancePersistenceChecklistDto> getNonCompliancePersistenceChecklist(Integer legalEntityCode, String auditTypeCode, String auditId){
			return auditObservationDao.getNonCompliancePersistenceChecklist(legalEntityCode, auditTypeCode, auditId);
		}
		
		@Override
		public void saveNonCompliancePersistenceRemarks(List<NonCompliancePersistenceChecklistDto> nonCompliancePersistenceChecklistDtoList){
			auditObservationDao.saveNonCompliancePersistenceRemarks(nonCompliancePersistenceChecklistDtoList);
		}
}