package com.bankaudit.rest.process.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.jboss.logging.Logger;
import org.springframework.beans.BeanUtils;
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.UserDao;
import com.bankaudit.dto.DataTableResponse;
import com.bankaudit.dto.process.AuditLetterBiLingualDto;
import com.bankaudit.dto.process.AuditLettersDto;
import com.bankaudit.dto.process.AuditLettersJasperDto;
import com.bankaudit.dto.process.AuditLettersStatementsJasperDto;
import com.bankaudit.dto.process.AuditObservationLetterDto;
import com.bankaudit.dto.process.LettersDto;
import com.bankaudit.dto.process.LettersSystemDataDto;
import com.bankaudit.process.model.AuditLetterBiLingual;
import com.bankaudit.process.model.AuditLetterBiLingualWrk;
import com.bankaudit.process.model.AuditLetterReportDocumentDetails;
import com.bankaudit.process.model.AuditLetterUserInputs;
import com.bankaudit.process.model.AuditLetterUserInputsHst;
import com.bankaudit.process.model.AuditLetterUserInputsWrk;
import com.bankaudit.process.model.AuditRating;
import com.bankaudit.process.model.AuditSchedule;
import com.bankaudit.process.model.AuditScheduleStagesStatusHst;
import com.bankaudit.rest.process.dao.LettersDao;
import com.bankaudit.rest.process.dao.LettersDaoImpl;
import com.bankaudit.rest.process.dao.MyAuditsDao;
import com.bankaudit.service.BusinessDateService;
import com.bankaudit.service.GeneralParameterService;
import com.bankaudit.service.GeneralTranslatorService;
import com.bankaudit.service.MaintEntityService;
import com.bankaudit.spring.config.BankAuditConfig;
import com.bankaudit.util.BankAuditUtil;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

@Service("letterService")
@Transactional("transactionManager")
public class LettersServiceImpl implements LettersService{
	
	@Autowired
	BusinessDateService businessDateService;
	
	@Autowired
	LettersDao lettersDao;
	
	@Autowired
	MyAuditsDao myAuditsDao;
	
	@Autowired
	InterfaceParameterService interfaceParameterService;
	
	@Autowired
	GeneralTranslatorService generalTranslatorService;
	
	@Autowired
	GeneralParameterService generalParameterService;
	
	@Autowired
	AuditObservationService auditObservationService;
	
	@Autowired
	UserDao userDao;
	
	@Autowired
	MaintEntityService maintEntityService;
	
	@Autowired
	AuditScheduleStagesStatusHstService auditScheduleStagesStatusHstService; 
	
	static final Logger logger = Logger.getLogger(LettersDaoImpl.class);
	
	@Override
	public List<LettersDto> getLettersByAuditId(int legalEntityCode, String auditTypeCode,String auditId,String role) {
		return lettersDao.getLettersByAuditId(legalEntityCode, auditTypeCode, auditId, role);
	}
	
	@Override
	public AuditLettersDto getLetterByAuditIdAndLetterCode(int legalEntityCode, String auditId,String letterCode, String status, String auditTypeCode) {
		if(auditTypeCode!=null);
		else auditTypeCode="RRBI";
		
		AuditLettersDto adtLtrDto = new AuditLettersDto();
		AuditSchedule auditSchedule = myAuditsDao.getAuditByAuditId(legalEntityCode, auditTypeCode, null, auditId);
		AuditSchedule auditSchedulePre = myAuditsDao.getAuditByAuditId(legalEntityCode, auditTypeCode, null, auditSchedule.getPrevAuditId());
		 		
		adtLtrDto = lettersDao.getLetterByAuditIdAndLetterCode(legalEntityCode,auditId,letterCode,status, auditTypeCode);
	    
		/*For setting Bi_Lingual Letter data*/
		if(BankAuditConstant.LETTER_CODE_FwdL.equalsIgnoreCase(letterCode)){
			AuditLettersDto adtLtrDtoBilinguan = lettersDao.getBiLingualLetterByAuditIdAndLetterCode(legalEntityCode, auditTypeCode, auditId, letterCode, status); 
		    if(!BankAuditConstant.STATUS_AUTH.equals(status)){
		    	adtLtrDto.setAuditLetterBiLingualWrkList(adtLtrDtoBilinguan.getAuditLetterBiLingualWrkList());	    	
		    }else{
		    	adtLtrDto.setAuditLetterBiLingualList(adtLtrDtoBilinguan.getAuditLetterBiLingualList());	    	
		    }
	    }else{
	    	adtLtrDto.setAuditLetterBiLingualList(new ArrayList<>());adtLtrDto.setAuditLetterBiLingualWrkList(new ArrayList<>());
	    }
	    			
		adtLtrDto.setLettersSysDataDto(lettersDao.getSystemDataByAuditIdAndLetterCode(legalEntityCode, auditId, letterCode, status)); // to get the User inputs
		adtLtrDto.setTranslatorMap(generalTranslatorService.getGeneralTranslatorKeyValue(legalEntityCode, "ALL", "hi", "LETTER", "HEADING", null, null));	
		
		if(!BankAuditConstant.LETTER_CODE_RN_Annexure_V.equalsIgnoreCase(letterCode)){
			Map<String, Object> properties = new HashMap<>();
			properties.put("legalEntityCode", legalEntityCode);
			properties.put("auditTypeCode", auditTypeCode);
			properties.put("auditId", auditId);		
			AuditRating auditRating =  (AuditRating)myAuditsDao.getUniqueEntityByMatchingProperties(AuditRating.class, properties);
			if(auditRating==null){
				auditRating =  new AuditRating();
			}
			Map<String, String> parameterMap = interfaceParameterService.getProfileDetailsByAuditId(legalEntityCode, auditId, null);		
			if(auditTypeCode.startsWith(BankAuditConstant.INSPECTION_TYPE_RRB_CONTAINS)){	 
				parameterMap.put("3BOM-653", auditRating.getSupervisoryRiskPrcntg());  //Rating,  
				parameterMap.put("3BOM-652", auditRating.getSupervisoryRating()); //category, 
			}else if(auditTypeCode.startsWith(BankAuditConstant.INSPECTION_TYPE_DCCB_CONTAIN)){		
				parameterMap.put("3BOMD637", auditRating.getSupervisoryRiskPrcntg());  //Rating 
				parameterMap.put("3BOMD638", auditRating.getSupervisoryRating()); //category
			}else if(auditTypeCode.startsWith(BankAuditConstant.INSPECTION_TYPE_StCB_CONTAIN)){		
				parameterMap.put("3BOMS650", auditRating.getSupervisoryRiskPrcntg());  //Rating 
				parameterMap.put("3BOMS651", auditRating.getSupervisoryRating()); //category
			}			  
			
			/***** Add Desk and Field/Onsite compliance rating ********/
			if(auditSchedulePre != null){
				parameterMap.put("complianceScoreDesk", auditSchedulePre.getDeskComplianceScore());
				parameterMap.put("complianceCategoryDesk", auditSchedulePre.getDeskComplianceRating());
				parameterMap.put("complianceScoreField", auditSchedulePre.getOnsiteComplianceScore());			
				parameterMap.put("complianceCategoryField", auditSchedulePre.getOnsiteComplianceRating());
			}
			/*******Set composite rating category*******/ 
			adtLtrDto.setCompositeRatingMap(lettersDao.getAuditRatingCompositeCategoryScoreByAuditId(legalEntityCode, auditTypeCode, auditId));
			
			adtLtrDto.setLatestParamMap(parameterMap); // to get the params
			adtLtrDto.setDliDpiParamMap(interfaceParameterService.getDliDpiDetailsByAuditId(legalEntityCode, auditId, null)); // to get the params	
			
			//To get the FY and Audit Serial no. for Directive letter
			if("Dr".equalsIgnoreCase(letterCode)) {
				AuditSchedule sch=myAuditsDao.getFYAndAuditSerialNoBfrInitiate(legalEntityCode, auditId, letterCode, adtLtrDto.getLettersSysDataDto().getUnitCode(), auditTypeCode, adtLtrDto.getLettersSysDataDto().getScheduleStartDate(), adtLtrDto.getLettersSysDataDto().getAuditStatus());
				if(sch!=null) {
					adtLtrDto.getLettersSysDataDto().setFinYrDate(sch.getFinancialYear());
					if(sch.getAuditSerialNo()!=null )
						adtLtrDto.getLettersSysDataDto().setSerialNoRoman(BankAuditUtil.integerToRomanNumeral(Integer.parseInt(sch.getAuditSerialNo().toString())));
				}
			}
			
			Map<String, AuditObservationLetterDto> ltMapAll =new HashMap<String, AuditObservationLetterDto>(); // to get the Standard and Derived statements
			Map<String, AuditObservationLetterDto> ltChkStndStmntMap =lettersDao.getChklstStmnts(legalEntityCode, auditId, letterCode, status, auditTypeCode);
			Map<String, AuditObservationLetterDto> ltDrivedStmntMap =lettersDao.getDeriveStmnts(legalEntityCode, auditId, letterCode, status, auditTypeCode);
			if(letterCode.contains("LoSC")) {
				ltDrivedStmntMap=getDerivestatementWithPositiveNegative(ltDrivedStmntMap, letterCode, auditTypeCode);
			}
			ltMapAll.putAll(ltChkStndStmntMap); ltMapAll.putAll(ltDrivedStmntMap);
			adtLtrDto.setChklstDrvStmntMap(ltMapAll);
		}else{ 
			adtLtrDto.setNonCompliancePersistenceChecklistDto(auditObservationService.getNonCompliancePersistenceChecklist(legalEntityCode, auditTypeCode, auditId));
		} 	
		return adtLtrDto;
	}
	
	@Override
	public void createAuditLetter(AuditLetterUserInputsWrk adtLtrWrk) {
		logger.info("Inside createAuditLetter .. "+ adtLtrWrk.getAuditId() +" :: "+adtLtrWrk.getStatus());
		try { 
			if(adtLtrWrk.getStatus().equalsIgnoreCase(BankAuditConstant.STATUS_DF) 
					|| adtLtrWrk.getStatus().equalsIgnoreCase(BankAuditConstant.STATUS_UNAUTH)){
				lettersDao.save(adtLtrWrk);			
				
				/*For saving Bi_Lingual Letter data*/
				if(BankAuditConstant.LETTER_CODE_FwdL.equalsIgnoreCase(adtLtrWrk.getLetterCode())){
					List<AuditLetterBiLingualWrk> auditLetterBiLingualWrkList = adtLtrWrk.getAuditLetterBiLingualWrkList();				
					if(adtLtrWrk !=null && auditLetterBiLingualWrkList!=null && auditLetterBiLingualWrkList.size()>0){						 
						for (AuditLetterBiLingualWrk auditLetterBiLingualWrk : auditLetterBiLingualWrkList) {
							auditLetterBiLingualWrk.setMakerTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(adtLtrWrk.getLegalEntityCode()));
							auditLetterBiLingualWrk.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(adtLtrWrk.getLegalEntityCode()));
							lettersDao.save(auditLetterBiLingualWrk);
						}					  
					}
				}				
			}/*else if (adtLtrWrk.getStatus().equalsIgnoreCase(BankAuditConstant.STATUS_AUTH)) {
				AuditLetterUserInputs adtLtr=new AuditLetterUserInputs();
				BeanUtils.copyProperties(adtLtrWrk, adtLtr);
				lettersDao.save(adtLtr);
			}*/
			
			if(BankAuditConstant.LETTER_CODE_RN_Annexure_V.equalsIgnoreCase(adtLtrWrk.getLetterCode())){
				auditObservationService.saveNonCompliancePersistenceRemarks(adtLtrWrk.getNonCompliancePersistenceChecklistDto());
			}
			if(adtLtrWrk.getStatus().equalsIgnoreCase(BankAuditConstant.STATUS_UNAUTH)){
				saveLetterStatusLogs(adtLtrWrk, BankAuditConstant.STATUS_UNAUTH);
			}
			
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
	}
	
	@Override
	public void updateAuditLetter(AuditLetterUserInputsWrk adtLtrWrk)  {
		logger.info("Inside updateAuditLetter .. "+ adtLtrWrk.getAuditId()+" :: "+adtLtrWrk.getStatus());
		try { 
			if(!adtLtrWrk.getStatus().equalsIgnoreCase(BankAuditConstant.STATUS_AUTH)){
				if(adtLtrWrk.getStatus().equalsIgnoreCase(BankAuditConstant.STATUS_UNAUTH) || adtLtrWrk.getStatus().equalsIgnoreCase(BankAuditConstant.STATUS_MOD)){
					AuditLetterUserInputsWrk adtLtrWrkTmp=lettersDao.getAuditLetterUserInputsWrk(adtLtrWrk.getLegalEntityCode(), adtLtrWrk.getAuditId(), adtLtrWrk.getLetterCode(), adtLtrWrk.getStatus());
					if(adtLtrWrkTmp !=null) {
						AuditLetterUserInputsHst adtLtrHst=new AuditLetterUserInputsHst();
						BeanUtils.copyProperties(adtLtrWrkTmp, adtLtrHst);
						lettersDao.save(adtLtrHst);
					}
					adtLtrWrk.setMakerTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(adtLtrWrk.getLegalEntityCode()));	
					saveLetterStatusLogs(adtLtrWrk, BankAuditConstant.STATUS_UNAUTH);
				}
				lettersDao.flushSession();
				lettersDao.saveOrUpdate(adtLtrWrk);	
				
				/*For saving Bi_Lingual Letter data*/
				if(BankAuditConstant.LETTER_CODE_FwdL.equalsIgnoreCase(adtLtrWrk.getLetterCode())){
					List<AuditLetterBiLingualWrk> auditLetterBiLingualWrkList = adtLtrWrk.getAuditLetterBiLingualWrkList();
					if(adtLtrWrk !=null && auditLetterBiLingualWrkList!=null && auditLetterBiLingualWrkList.size()>0){						  
						for (AuditLetterBiLingualWrk auditLetterBiLingualWrk : auditLetterBiLingualWrkList) {
							auditLetterBiLingualWrk.setMakerTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(adtLtrWrk.getLegalEntityCode()));
							auditLetterBiLingualWrk.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(adtLtrWrk.getLegalEntityCode()));
							lettersDao.saveOrUpdate(auditLetterBiLingualWrk);
						}						 
					}
				}	
				if(adtLtrWrk.getStatus().equalsIgnoreCase(BankAuditConstant.STATUS_REJ)){
					saveLetterStatusLogs(adtLtrWrk, BankAuditConstant.STATUS_REJ);
				} 
			}else{
				AuditLetterUserInputs adtLtr=new AuditLetterUserInputs();
				BeanUtils.copyProperties(adtLtrWrk, adtLtr);
				adtLtr.setCheckerTimestamp(adtLtr.getBusinessdateTimestamp());
				lettersDao.saveOrUpdate(adtLtr);
				
				/*For saving Bi_Lingual Letter data*/
				if(BankAuditConstant.LETTER_CODE_FwdL.equalsIgnoreCase(adtLtrWrk.getLetterCode())){
					List<AuditLetterBiLingualWrk> auditLetterBiLingualWrkList = adtLtrWrk.getAuditLetterBiLingualWrkList();
					if(auditLetterBiLingualWrkList!=null && auditLetterBiLingualWrkList.size()>0){
						Date checkerTimestamp = businessDateService.getBusinessDateTimestampByLegalEntityCode(adtLtr.getLegalEntityCode());
						for (AuditLetterBiLingualWrk auditLetterBiLingualWrk : auditLetterBiLingualWrkList) {
							AuditLetterBiLingual auditLetterBiLingual=new AuditLetterBiLingual();
							BeanUtils.copyProperties(auditLetterBiLingualWrk, auditLetterBiLingual);
							auditLetterBiLingual.setCheckerTimestamp(checkerTimestamp);
							auditLetterBiLingual.setId(null);
							lettersDao.save(auditLetterBiLingual);
						}
					}
				}
				lettersDao.deleteAuditLetterInput(adtLtrWrk.getLegalEntityCode(), adtLtrWrk.getAuditId(), adtLtrWrk.getLetterCode(), BankAuditConstant.STATUS_UNAUTH);

				saveLetterStatusLogs(adtLtrWrk, BankAuditConstant.STATUS_AUTH);
			}
			
			if(BankAuditConstant.LETTER_CODE_RN_Annexure_V.equalsIgnoreCase(adtLtrWrk.getLetterCode())){
				auditObservationService.saveNonCompliancePersistenceRemarks(adtLtrWrk.getNonCompliancePersistenceChecklistDto());
			}			 
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
	} 
	
	@Override
	public void deleteAuditLetterByIdCode(int legalEntityCode, String auditId,String letterCode, String status) {
		lettersDao.deleteAuditLetterByIdCode(legalEntityCode, auditId, letterCode, status);
	}
	
	@Override
	public Boolean isAuthAllowed(Integer legalEntityCode, String auditId,String letterCode, String userId) {
		return lettersDao.isAuthAllowed(legalEntityCode, auditId, letterCode, userId);
	}
	
	// Method to mark the derive statement as Positive or Negative
	public Map<String, AuditObservationLetterDto> getDerivestatementWithPositiveNegative(Map<String, AuditObservationLetterDto> drMap, String letterCode, String auditTypeCode) {
		logger.info("Inside getDerivestatementWithPositiveNegative .. "+ drMap + " auditTypeCode:: "+ auditTypeCode);
		Map<String, AuditObservationLetterDto> drUpdtMap= new HashMap<>();
		try {
			for (Map.Entry<String,AuditObservationLetterDto> entry : drMap.entrySet()) {
				logger.info("Key .. "+entry.getKey() +" Value .."+entry.getValue());
				AuditObservationLetterDto dto=entry.getValue();
				String drOPst=dto.getDeriveStatementOPStmnt();
				logger.info("drOPst .. "+drOPst+" StmntID:: "+dto.getStatementId());
				if("DCCBI".equalsIgnoreCase(auditTypeCode) || "DCCBEI".equalsIgnoreCase(auditTypeCode)) { // for AuditTypeCode DCCBI and DCCBEI
					// Used contains instead of equalsIgnoreCase, to handle both StCB and StCBEI
					if(dto.getStatementId().equalsIgnoreCase("201DCCB") && drOPst!=null  
							&& (drOPst.equals("13") || drOPst.equals("14") || drOPst.equals("5") || drOPst.equals("15"))) { // && (drOPst.equals("5") || drOPst.equals("6") || drOPst.equals("7") || drOPst.equals("8"))) {
						dto.setDerivedStatementIsNegetive(true);
					}else if(("2").equals(drOPst) && 
							( dto.getStatementId().contains("218DCCB") || dto.getStatementId().contains("223DCCB") ||
							  dto.getStatementId().contains("659DCCB") || dto.getStatementId().contains("616DCCB") ||
							  dto.getStatementId().contains("628DCCB") || dto.getStatementId().contains("631DCCB"))) {
						dto.setDerivedStatementIsNegetive(true);
					}else if(("1").equals(drOPst) && 
							( dto.getStatementId().contains("221DCCB") || dto.getStatementId().contains("355DCCB") )) {
						dto.setDerivedStatementIsNegetive(true);
					}else if(("0").equals(drOPst) && 
							( dto.getStatementId().contains("814DCCB") || dto.getStatementId().contains("815DCCB") ||
							  dto.getStatementId().contains("361DCCB") || dto.getStatementId().contains("210DCCB")) ) {
						dto.setDerivedStatementIsNegetive(true);
					}
				}else if("SCRDB".equalsIgnoreCase(auditTypeCode)) { // for AuditTypeCode SCRDB
					if(dto.getStatementId().equalsIgnoreCase("XXXXXDS") && drOPst!=null  
							&& (drOPst.equals("13") || drOPst.equals("14") || drOPst.equals("5") || drOPst.equals("15"))) { // && (drOPst.equals("5") || drOPst.equals("6") || drOPst.equals("7") || drOPst.equals("8"))) {
						dto.setDerivedStatementIsNegetive(true);
					}else if(("2").equals(drOPst) && 
							( dto.getStatementId().equalsIgnoreCase("XXXXXDS") || dto.getStatementId().equalsIgnoreCase("XXXXXDS") )) {
						dto.setDerivedStatementIsNegetive(true);
					}else if(("1").equals(drOPst) && 
							( dto.getStatementId().equalsIgnoreCase("XXXXXDS") || dto.getStatementId().equalsIgnoreCase("XXXXXDS") || 
							  dto.getStatementId().equalsIgnoreCase("XXXXXDS") || 
							  dto.getStatementId().equalsIgnoreCase("XXXXXDS") || dto.getStatementId().equalsIgnoreCase("XXXXXDS"))) {
						dto.setDerivedStatementIsNegetive(true);
					}else if(("0").equals(drOPst) && 
							( dto.getStatementId().equalsIgnoreCase("XXXXXDS"))) {
								dto.setDerivedStatementIsNegetive(true);
					}
				}else if("StCBI".equalsIgnoreCase(auditTypeCode) || "StCBEI".equalsIgnoreCase(auditTypeCode) ) { // for AuditTypeCode StCBI or StCBEI
					// Used contains instead of equalsIgnoreCase, to handle both StCB and StCBEI
					if(dto.getStatementId().contains("201STCB") && drOPst!=null  
							&& (drOPst.equals("13") || drOPst.equals("14") || drOPst.equals("5") || drOPst.equals("15"))) { // && (drOPst.equals("5") || drOPst.equals("6") || drOPst.equals("7") || drOPst.equals("8"))) {
						dto.setDerivedStatementIsNegetive(true);
					}else if(("2").equals(drOPst) && 
							( dto.getStatementId().contains("222STCB") || dto.getStatementId().contains("215STCB") || dto.getStatementId().contains("224STCB") ||
							  dto.getStatementId().contains("358STCB") || dto.getStatementId().contains("655STCB") ||
							  dto.getStatementId().contains("624STCB") || dto.getStatementId().contains("655STCB") )) {
						dto.setDerivedStatementIsNegetive(true);
					}else if(("1").equals(drOPst) && 
							( dto.getStatementId().contains("616STCB"))) {
						dto.setDerivedStatementIsNegetive(true);
					}else if(("0").equals(drOPst) && 
							( dto.getStatementId().contains("81StCB"))) {
								dto.setDerivedStatementIsNegetive(true);
					}else if( (("99").equals(drOPst) || ("0").equals(drOPst)) &&   // 99 won't store in audit report stmnt table so, use 0
							( dto.getStatementId().contains("627STCB") || dto.getStatementId().contains("814STCB") ||
						      dto.getStatementId().contains("815STCB") || dto.getStatementId().contains("366STCB") ||
						      dto.getStatementId().contains("212STCB"))) {
						dto.setDerivedStatementIsNegetive(true);
					}
				}else { // for AuditTypeCode RRBI and RRBEI
					if(dto.getStatementId().equalsIgnoreCase("13RRB") && drOPst!=null  
							&& (drOPst.equals("13") || drOPst.equals("14") || drOPst.equals("5") || drOPst.equals("15"))) { // && (drOPst.equals("5") || drOPst.equals("6") || drOPst.equals("7") || drOPst.equals("8"))) {
						dto.setDerivedStatementIsNegetive(true);
					}else if(("2").equals(drOPst) && 
							( dto.getStatementId().contains("210RRB") || dto.getStatementId().contains("31RRB") )) {
						dto.setDerivedStatementIsNegetive(true);
					}else if(("1").equals(drOPst) && 
							( dto.getStatementId().contains("23RRB") || dto.getStatementId().contains("30RRB") || 
							  dto.getStatementId().contains("77RRB") || 
							  dto.getStatementId().contains("143RRB") || dto.getStatementId().contains("144RRB"))) {
						dto.setDerivedStatementIsNegetive(true);
					}else if(("0").equals(drOPst) && 
							( dto.getStatementId().contains("81RRB") || dto.getStatementId().contains("280RRB"))) {
								dto.setDerivedStatementIsNegetive(true);
					}else if(("99").equals(drOPst) && 
							( dto.getStatementId().contains("280RRB"))) {
								dto.setDerivedStatementIsNegetive(true);
					}
				}
				drUpdtMap.put(entry.getKey(), dto);
			}
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}return drUpdtMap;
	}
	
	@Override
	public String  saveLetterPDFByAuditIdAndLetterCode(Map<String, Object> params, int legalEntityCode, String auditId, String letterCode, 
			String status, String auditTypeCode, String userId) {
		logger.info("Inside saveLetterPDFByAuditIdAndLetterCode .."+ legalEntityCode +" :: "+auditId+" :: "+letterCode+" :: "+status  +" :: "+ auditTypeCode);
		 		
		AuditLettersDto adtLtrDto= lettersDao.getLetterByAuditIdAndLetterCode(legalEntityCode,auditId,letterCode,status,auditTypeCode);
			
		Map<String, Object> properties = new HashMap<>();
		properties.put("legalEntityCode", legalEntityCode);
		properties.put("auditTypeCode", auditTypeCode);
		properties.put("auditId", auditId);		
		AuditRating auditRating =  (AuditRating)myAuditsDao.getUniqueEntityByMatchingProperties(AuditRating.class, properties);
		if(auditRating==null){
			auditRating =  new AuditRating();
		}
		AuditSchedule auditSchedule = myAuditsDao.getAuditByAuditId(legalEntityCode, auditTypeCode, null, auditId);
		AuditSchedule auditSchedulePre = myAuditsDao.getAuditByAuditId(legalEntityCode, auditTypeCode, null, auditSchedule.getPrevAuditId());
		try{
			if(adtLtrDto == null || auditSchedule==null) 
				{
					//adtLtrDto= new AuditLettersDto(); 
					return  BankAuditConstant.FAILED;
				}
			 
			AuditLettersJasperDto auditLettersJasperDto = new AuditLettersJasperDto();		
			//Set User Inputs
			if(adtLtrDto.getAdtLtr()!=null){
				BeanUtils.copyProperties(adtLtrDto.getAdtLtr(), auditLettersJasperDto);
			}else if(adtLtrDto.getAdtLtrWrk()!=null){
				BeanUtils.copyProperties(adtLtrDto.getAdtLtrWrk(), auditLettersJasperDto);
			}
			
			String jasperReportName = "";
			String letterName = "";
			String letterDocumentTypeCode = "";
			String[] stmtKeys = new String[]{};
			
			if(letterCode.equalsIgnoreCase(BankAuditConstant.LETTER_CODE_FwdL)){
				jasperReportName ="ForwardingLetter.jrxml";
				letterName ="ForwardingLetter";
			}else if(letterCode.equalsIgnoreCase(BankAuditConstant.LETTER_CODE_HoR)){
				jasperReportName ="HoR.jrxml";
				letterName ="HeadOfficeRecomm";
				letterDocumentTypeCode = BankAuditConstant.LETTER_DOC_TYPE_CODE_HoRRoR;
				stmtKeys = new String[] {"I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","XIII","XIV","XV","XVI","XVII","XVIII","XIX","XX","XXI","XXII",
						"XXIII","XXIV","XXV","XXVI","XXVII"};
				
				if(auditTypeCode.startsWith(BankAuditConstant.INSPECTION_TYPE_DCCB_CONTAIN)){
					stmtKeys = new String[] {"I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","XIII","XIV","XV","XVI","XVII","XVIII","XIX","XX","XXI","XXII",
							"XXIII","XXIV","XXV","XXVI","XXVII","XXVIII","XXIX","XXX","XXXI","XXXII","XXXIII","XXXIV","XXXV","XXXVI","XXXVII","XXXVIII"};
				}
				else if(auditTypeCode.startsWith(BankAuditConstant.INSPECTION_TYPE_StCB_CONTAIN)){
					stmtKeys = new String[] {"I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","XIII","XIV","XV","XVI","XVII","XVIII","XIX","XX","XXI","XXII",
							"XXIII","XXIV","XXV","XXVI","XXVII","XXVIII","XXIX","XXX","XXXI","XXXII","XXXIII","XXXIV","XXXV","XXXVI","XXXVII","XXXVIII","XXXIX",
							"XL"};
				}
			}else if(letterCode.equalsIgnoreCase(BankAuditConstant.LETTER_CODE_RoR)){
				jasperReportName ="RoR.jrxml";
				letterName ="RegionalOfficeRecomm";
				letterDocumentTypeCode = BankAuditConstant.LETTER_DOC_TYPE_CODE_HoRRoR;
				stmtKeys = new String[] {"I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","XIII","XIV","XV","XVI","XVII","XVIII","XIX","XX","XXI","XXII",
						"XXIII","XXIV","XXV","XXVI","XXVII"};
				
				if(auditTypeCode.startsWith(BankAuditConstant.INSPECTION_TYPE_DCCB_CONTAIN)){
					stmtKeys = new String[] {"I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","XIII","XIV","XV","XVI","XVII","XVIII","XIX","XX","XXI","XXII",
							"XXIII","XXIV","XXV","XXVI","XXVII","XXVIII","XXIX","XXX","XXXI","XXXII","XXXIII","XXXIV","XXXV","XXXVI","XXXVII","XXXVII"};
				}
				else if(auditTypeCode.startsWith(BankAuditConstant.INSPECTION_TYPE_StCB_CONTAIN)){
					stmtKeys = new String[] {"I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","XIII","XIV","XV","XVI","XVII","XVIII","XIX","XX","XXI","XXII",
							"XXIII","XXIV","XXV","XXVI","XXVII","XXVIII","XXIX","XXX","XXXI","XXXII","XXXIII","XXXIV","XXXV","XXXVI","XXXVII","XXXVIII","XXXIX",
							"XL"};
				}
			}else if(letterCode.equalsIgnoreCase(BankAuditConstant.LETTER_CODE_RN)){
				jasperReportName ="RecommendaryNote.jrxml";
				letterName ="RecommendaryNote";
				letterDocumentTypeCode = BankAuditConstant.LETTER_DOC_TYPE_CODE_RN;
			}else if(letterCode.equalsIgnoreCase(BankAuditConstant.LETTER_CODE_HoLoSC)){
				jasperReportName ="HoLoSC.jrxml";	
				letterName ="HOSupervisoryConcern";
				letterDocumentTypeCode = BankAuditConstant.LETTER_DOC_TYPE_CODE_HoRoLoSC;
				stmtKeys = new String[] {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31",
						"32","33","34","35"};
				
				if(auditTypeCode.startsWith(BankAuditConstant.INSPECTION_TYPE_DCCB_CONTAIN)){
					stmtKeys = new String[] {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30",
							"31","32","33","34","35","36","37","38","39","40","41","42"};
				}
				else if(auditTypeCode.startsWith(BankAuditConstant.INSPECTION_TYPE_StCB_CONTAIN)){
					stmtKeys = new String[] {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30",
							"31","32","33","34","35","36","37","38","39","40","41","42","43"};
				}
			}
			else if(letterCode.equalsIgnoreCase(BankAuditConstant.LETTER_CODE_RoLoSC)){
				jasperReportName ="RoLoSC.jrxml";
				letterName ="ROSupervisoryConcern";
				letterDocumentTypeCode = BankAuditConstant.LETTER_DOC_TYPE_CODE_HoRoLoSC;				
				stmtKeys = new String[] {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31",
						"32","33","34","35"};
				
				if(auditTypeCode.startsWith(BankAuditConstant.INSPECTION_TYPE_DCCB_CONTAIN)){
					stmtKeys = new String[] {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30",
							"31","32","33","34","35","36","37","38","39","40","41","42"};
				}
				else if(auditTypeCode.startsWith(BankAuditConstant.INSPECTION_TYPE_StCB_CONTAIN)){
					stmtKeys = new String[] {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30",
							"31","32","33","34","35","36","37","38","39","40","41","42","43"};
				}
			}else if(letterCode.equalsIgnoreCase(BankAuditConstant.LETTER_CODE_Directive)){
				jasperReportName ="DirectiveLetter.jrxml";
				letterName ="DirectiveLetter";			 
			}else if(letterCode.equalsIgnoreCase(BankAuditConstant.LETTER_CODE_RN_Annexure_V)){
				jasperReportName ="RNAnnexureV.jrxml";
				letterName ="RNAnnexureV";	
			}else{
				return  BankAuditConstant.FAILED;
			}
			
			LettersSystemDataDto lettersSystemDataDto = lettersDao.getSystemDataByAuditIdAndLetterCode(legalEntityCode, auditId, letterCode, status);
			if(letterCode.equalsIgnoreCase(BankAuditConstant.LETTER_CODE_Directive)){ //Get the financial year and Roman number before initiation 
				AuditSchedule sch=myAuditsDao.getFYAndAuditSerialNoBfrInitiate(legalEntityCode, auditId, letterCode, lettersSystemDataDto.getUnitCode(), auditTypeCode, lettersSystemDataDto.getScheduleStartDate(), lettersSystemDataDto.getAuditStatus());
				if(sch!=null) {
					lettersSystemDataDto.setFinYrDate(sch.getFinancialYear());
					if(sch.getAuditSerialNo()!=null )
						lettersSystemDataDto.setSerialNoRoman(BankAuditUtil.integerToRomanNumeral(Integer.parseInt(sch.getAuditSerialNo().toString())));
				}
			}
			
			Map<String, String> translatorMap = generalTranslatorService.getGeneralTranslatorKeyValue(legalEntityCode, "ALL", "hi", "LETTER", "HEADING", null, null);
			auditLettersJasperDto.setHO(translatorMap.get("HO"));
			auditLettersJasperDto.setRO(translatorMap.get("RO"));
			auditLettersJasperDto.setNABARD(translatorMap.get("NABARD"));
			auditLettersJasperDto.setSUPERVISION(translatorMap.get("SUPERVISION"));
			auditLettersJasperDto.setHO_CITY(translatorMap.get("HO_CITY"));
			if(lettersSystemDataDto!=null){
				BeanUtils.copyProperties(lettersSystemDataDto, auditLettersJasperDto);
			}
				
			String letterPath = null; 
			String subReportDir = "/letters/";		
			if(!letterCode.equalsIgnoreCase(BankAuditConstant.LETTER_CODE_RN_Annexure_V)){
				Map<String, AuditObservationLetterDto> ltChkStndStmntMap =lettersDao.getChklstStmnts(legalEntityCode, auditId, letterCode, status, auditTypeCode);
				Map<String, AuditObservationLetterDto> ltDrivedStmntMap =lettersDao.getDeriveStmnts(legalEntityCode, auditId, letterCode, status, auditTypeCode);
				if(letterCode.contains("LoSC")) {
					ltDrivedStmntMap=getDerivestatementWithPositiveNegative(ltDrivedStmntMap, letterCode, auditTypeCode);
				}		
				Map<String, AuditObservationLetterDto> chklstDrvStmntMap = new HashMap<String, AuditObservationLetterDto>();
				chklstDrvStmntMap.putAll(ltChkStndStmntMap);
				chklstDrvStmntMap.putAll(ltDrivedStmntMap);		
							
				if(auditTypeCode.startsWith(BankAuditConstant.INSPECTION_TYPE_RRB_CONTAINS)){				
					auditLettersJasperDto = processRRBLetters(letterCode, legalEntityCode, auditId,	auditLettersJasperDto,chklstDrvStmntMap, stmtKeys, auditRating, auditSchedulePre);		
					letterPath = "/letters/RRB_letters/";  
				}else if(auditTypeCode.startsWith(BankAuditConstant.INSPECTION_TYPE_DCCB_CONTAIN)){		
					auditLettersJasperDto = processDCCBLetters(letterCode, legalEntityCode, auditId,	auditLettersJasperDto,chklstDrvStmntMap, stmtKeys, auditRating, auditSchedulePre);	
					letterPath = "/letters/DCCB_letters/DCCB_"; 
				}else if(auditTypeCode.startsWith(BankAuditConstant.INSPECTION_TYPE_StCB_CONTAIN)){		
					auditLettersJasperDto = processStCBLetters(letterCode, legalEntityCode, auditId,	auditLettersJasperDto,chklstDrvStmntMap, stmtKeys, auditRating, auditSchedulePre);	
					letterPath = "/letters/StCB_letters/StCB_"; 
				}	
				
				for (int len=1; len<=80; len++) {			    
					String userInput = "userInput"+String.format("%02d", len );				 
					Object userInputObject = org.apache.commons.beanutils.PropertyUtils.getSimpleProperty(auditLettersJasperDto, userInput);
					if(userInputObject!=null && !"".equals(userInputObject.toString())){					
						Field userInputFiled = auditLettersJasperDto.getClass().getDeclaredField(userInput);
						userInputFiled.setAccessible(true); 
						userInputFiled.set(auditLettersJasperDto, userInputObject.toString().replaceAll("(\r\n|\n\r|\n|\r)", "<br>"));
					}   					
				}
			}else{
				letterPath = "/letters/";				
				auditLettersJasperDto.setNonCompliancePersistenceChecklistDtoList(auditObservationService.getNonCompliancePersistenceChecklist(legalEntityCode, auditTypeCode, auditId));
			}
			if(letterPath==null){
				return  BankAuditConstant.FAILED; 
			}
					
			if(BankAuditConstant.STATUS_UNAUTH.equalsIgnoreCase(status)){
				auditLettersJasperDto.setPageInfo(new SimpleDateFormat("ddMMyyyy-HHmm").format(new Date())+"-"+userId);
				auditLettersJasperDto.setPageInfoAlign("L");
				params.put("pageInfoAlign", "L");
			}else{
				Map<String, String> generalParameter = generalParameterService.getGeneralParameterKeyValue(legalEntityCode, "", "", "STATUS", "STATUS", "", "");
				auditLettersJasperDto.setPageInfo(new SimpleDateFormat("ddMMyyyy").format(new Date())+"-"+userId+"-"+generalParameter.get(status));
				auditLettersJasperDto.setPageInfoAlign("R");
				params.put("pageInfoAlign", "R");
			}
			/*auditLettersJasperDto.setPageInfo(userId+"-"+new SimpleDateFormat("ddMMyyyy").format(new Date())
					+"-"+(BankAuditConstant.STATUS_UNAUTH.equalsIgnoreCase(status)?"UnAuthorised":"Authorised")); */
			
			/*******Set composite rating category*******/ 
			auditLettersJasperDto.setCompositeRatingMap(lettersDao.getAuditRatingCompositeCategoryScoreByAuditId(legalEntityCode, auditTypeCode, auditId));
			
			/*******************Start Set respective BiLingual letter***********************/
			if(BankAuditConstant.LETTER_CODE_FwdL.equalsIgnoreCase(letterCode)){
				AuditLettersDto auditLettersDtoBiLingual = lettersDao.getBiLingualLetterByAuditIdAndLetterCode(legalEntityCode, auditTypeCode, auditId, letterCode, status);
				if(auditLettersDtoBiLingual!=null){
					List<AuditLetterBiLingualDto> auditLetterBiLingualDtoList = new ArrayList<>();
					if(!BankAuditConstant.STATUS_AUTH.equalsIgnoreCase(status)){
						List<AuditLetterBiLingualWrk> auditLetterBiLingualWrkList = auditLettersDtoBiLingual.getAuditLetterBiLingualWrkList();
						for (AuditLetterBiLingualWrk auditLetterBiLingualWrk : auditLetterBiLingualWrkList) {
							AuditLetterBiLingualDto auditLetterBiLingualDto = new AuditLetterBiLingualDto();
							BeanUtils.copyProperties(auditLetterBiLingualWrk, auditLetterBiLingualDto); 
							auditLetterBiLingualDtoList.add(auditLetterBiLingualDto);
						}
					}else{
						List<AuditLetterBiLingual> auditLetterBiLingualList = auditLettersDtoBiLingual.getAuditLetterBiLingualList();
						for (AuditLetterBiLingual auditLetterBiLingual : auditLetterBiLingualList) {
							AuditLetterBiLingualDto auditLetterBiLingualDto = new AuditLetterBiLingualDto();
							BeanUtils.copyProperties(auditLetterBiLingual, auditLetterBiLingualDto); 
							auditLetterBiLingualDtoList.add(auditLetterBiLingualDto);
						}
					}
					auditLettersJasperDto.setAuditLetterBiLingualDtoList(auditLetterBiLingualDtoList);
				} 
			}
			/*******************End Set respective BiLingual letter***********************/
			
			
			List<AuditLettersJasperDto> jasperReportBeanDataSourceList = new ArrayList<AuditLettersJasperDto>();	
			jasperReportBeanDataSourceList.add(auditLettersJasperDto);			
			 
			InputStream stream = this.getClass().getResourceAsStream(letterPath + jasperReportName);			 
			JasperReport jasperReport   = JasperCompileManager.compileReport(stream);
			params.put("SUB_REPORT_DIR", subReportDir);
			params.put("SUB_REPORT_DIR_BI_LINGUAL_FWDL", "/letters/");
			 
			 		 
			JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(jasperReportBeanDataSourceList);
			JasperPrint print = JasperFillManager.fillReport(jasperReport, params, dataSource);			 
			
			String uploadFileName = legalEntityCode+"_"+auditId+"_"+letterCode+"_TMP_"+new SimpleDateFormat("ddMMyyyy").format(new Date())+"_"+letterName+".pdf";			
			String generatedLettersPath = BankAuditConfig.getInstance().getConfigValue(BankAuditConstant.DIR_DOC_UPLOAD_JASPER_TMP)+ "/" +uploadFileName;
			JasperExportManager.exportReportToPdfFile(print, generatedLettersPath); 
			
			/*JRDocxExporter exporter = new JRDocxExporter();
			exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
			exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, "D://myreport.docx");
			exporter.exportReport();*/
			
			if(BankAuditConstant.STATUS_AUTH.equalsIgnoreCase(status)){					
				//merge letters 
				generatedLettersPath = mergeLettesAndUploadedPdf(legalEntityCode, auditId, auditTypeCode, letterDocumentTypeCode, generatedLettersPath, letterName, true);				
				//save letters									 
				if(generatedLettersPath!=null){
					String uploadStatus = saveAuditLetters(adtLtrDto.getAdtLtr(), legalEntityCode, auditId, letterCode, generatedLettersPath, uploadFileName);			
					return uploadStatus;
				} 
			}else if(BankAuditConstant.STATUS_UNAUTH.equalsIgnoreCase(status)){			 
				//merge letters 
				generatedLettersPath = mergeLettesAndUploadedPdf(legalEntityCode, auditId, auditTypeCode, letterDocumentTypeCode, generatedLettersPath, letterName, false);
				return generatedLettersPath;
			}						 	
			 
		} catch (JRException  e) {
			logger.error("Error .. JRException .." + e.getMessage()+" :: "+e.getCause()); 
			e.printStackTrace(System.out);
		}catch (Exception e) {
			logger.error("Error .. Exception .." + e.getMessage()+" :: "+e.getCause()); 
			e.printStackTrace(System.out);
		}   
		return  BankAuditConstant.FAILED;
	}
	
	private String saveAuditLetters( AuditLetterUserInputs adtLtr, int legalEntityCode, String auditId, String letterCode, String referencePath, String fileName){
		logger.info(" Inside saveAuditLetters .. ");
		try{
			AuditLetterReportDocumentDetails auditLettersReportsDocumentDetails =  new AuditLetterReportDocumentDetails();
			auditLettersReportsDocumentDetails.setLegalEntityCode(legalEntityCode);
			auditLettersReportsDocumentDetails.setAuditTypeCode(adtLtr.getAuditTypeCode()); 
			auditLettersReportsDocumentDetails.setAuditId(auditId);
			auditLettersReportsDocumentDetails.setPlanId(adtLtr.getPlanId());
			auditLettersReportsDocumentDetails.setUnitId(adtLtr.getUnitId());  		
			auditLettersReportsDocumentDetails.setDocumentType("Letter");  
			auditLettersReportsDocumentDetails.setDocumentName(letterCode);  
			auditLettersReportsDocumentDetails.setMaker(adtLtr.getMaker());  			 
			auditLettersReportsDocumentDetails.setMakerTimestamp(adtLtr.getMakerTimestamp());
			auditLettersReportsDocumentDetails.setUserRoleId("");					
			auditLettersReportsDocumentDetails.setLetterCode(letterCode); 
			auditLettersReportsDocumentDetails.setChecker(adtLtr.getChecker());
			auditLettersReportsDocumentDetails.setCheckerTimestamp(adtLtr.getCheckerTimestamp());
			auditLettersReportsDocumentDetails.setStatus(BankAuditConstant.STATUS_ACTIVE);
			auditLettersReportsDocumentDetails.setAuthRejRemarks(adtLtr.getAuthRejRemarks());
			auditLettersReportsDocumentDetails.setReferencePath(referencePath); 
			auditLettersReportsDocumentDetails.setFileName(fileName);			
			lettersDao.save(auditLettersReportsDocumentDetails);			
		}catch (Exception e) {
			logger.error("Error .. SaveAuditLetters " + e.getMessage()+" :: "+e.getCause());
			e.printStackTrace(System.out);
			return  BankAuditConstant.FAILED;
		}
		return BankAuditConstant.SUCCESS;
		
	}

	@Override
	public String getDocReferencePath(int legalEntityCode, String auditId, String letterCode, String auditTypeCode){
		return lettersDao.getDocReferencePath(legalEntityCode, auditId, letterCode, auditTypeCode);
	}
	 
	private AuditLettersJasperDto processRRBLetters(String letterCode,int legalEntityCode, String auditId,
			AuditLettersJasperDto auditLettersJasperDto, Map<String, AuditObservationLetterDto> chklstDrvStmntMap,
			 String[] stmtKeys, AuditRating auditRating, AuditSchedule auditSchedulePre) throws  NoSuchMethodException, IllegalAccessException, InvocationTargetException{
		
		List<AuditLettersStatementsJasperDto> statementsRemarksList = new ArrayList<AuditLettersStatementsJasperDto>();	
		Map<String, String> parameterChklstDrvStmntMap =  new HashMap<String, String>();
		Map<String, String> parameterMap = interfaceParameterService.getProfileDetailsByAuditId(legalEntityCode, auditId, null);
		
		/***** Add Desk and Field/Onsite compliance rating ********/
		if(auditSchedulePre!=null){
			parameterMap.put("complianceScoreDesk", auditSchedulePre.getDeskComplianceScore());
			parameterMap.put("complianceCategoryDesk", auditSchedulePre.getDeskComplianceRating());
			parameterMap.put("complianceScoreField", auditSchedulePre.getOnsiteComplianceScore());			
			parameterMap.put("complianceCategoryField", auditSchedulePre.getOnsiteComplianceRating());
		}
		
		if(letterCode.contains("LoSC")){
			for (int len=0 ;  len<stmtKeys.length ; len++) {
				
				AuditLettersStatementsJasperDto statements =  new AuditLettersStatementsJasperDto();				
				statements.setSrNo(stmtKeys[len]); 
				String userInput = "userInput"+String.format("%02d", (80-len) );				 
				Object userInputObject = org.apache.commons.beanutils.PropertyUtils.getSimpleProperty(auditLettersJasperDto, userInput);
				if(userInputObject!=null && !"".equals(userInputObject.toString())){
					statements.setStatementsRemarks(userInputObject.toString()); 
				}                 
				statementsRemarksList.add(statements);					
					
				/***************** START OLD CODE  ****************				 
				AuditObservationLetterDto auditObservationLetterDto = chklstDrvStmntMap.get(seqNo);
				if(auditObservationLetterDto!=null){
					
					if(seqNo.equalsIgnoreCase("3") || seqNo.equalsIgnoreCase("4") || seqNo.equalsIgnoreCase("6")
							|| seqNo.equalsIgnoreCase("9") || seqNo.equalsIgnoreCase("10") || seqNo.equalsIgnoreCase("11")
							|| seqNo.equalsIgnoreCase("13") || seqNo.equalsIgnoreCase("14") || seqNo.equalsIgnoreCase("15")
							|| seqNo.equalsIgnoreCase("16") || seqNo.equalsIgnoreCase("17") || seqNo.equalsIgnoreCase("19")
							|| seqNo.equalsIgnoreCase("20") || seqNo.equalsIgnoreCase("21") || seqNo.equalsIgnoreCase("22") ){
					//if(BankAuditUtil.isEmptyString(auditObservationLetterDto.getDerivedStatement())){
						if(BankAuditConstant.COMPLIANCE_YES.equalsIgnoreCase(auditObservationLetterDto.getComplianceCategory()) 
								&& !BankAuditConstant.NO.equalsIgnoreCase(auditObservationLetterDto.getStandardStmntCompliancePrint())){
							// if Compliance no print
							//statements.setStatementsRemarks(auditObservationLetterDto.getStandardStmntCompliance());					
						}else if(BankAuditConstant.COMPLIANCE_NO.equalsIgnoreCase(auditObservationLetterDto.getComplianceCategory()) 
								&& !BankAuditConstant.NO.equalsIgnoreCase(auditObservationLetterDto.getStandardStmntNonCompliancePrint())){
							
							String standardStmt1=auditObservationLetterDto.getStandardStmntNonCompliance()==null?"":auditObservationLetterDto.getStandardStmntNonCompliance()+"<br/>";
							String standardStmt2=auditObservationLetterDto.getFindingRemarks()==null?"":auditObservationLetterDto.getFindingRemarks();
							statements.setStatementsRemarks(standardStmt1+ "" + standardStmt2);			
							//statements.setStatementsRemarks(auditObservationLetterDto.getFindingRemarks());
							
						}
					}else{
						if(auditObservationLetterDto.isDerivedStatementIsNegetive()){
							statements.setStatementsRemarks(auditObservationLetterDto.getDerivedStatement());
						}
					}						 
				}
				statementsRemarksList.add(statements);
				***************** END OLD CODE  ****************/			
			}
			
			AuditLettersStatementsJasperDto statements =  new AuditLettersStatementsJasperDto();
			
			statements.setSrNo("26");
			statements.setStatementsRemarks(auditLettersJasperDto.getUserInput08());  
			statementsRemarksList.set(25, statements);
			
			statements =  new AuditLettersStatementsJasperDto();
			statements.setSrNo("27");
			statements.setStatementsRemarks(auditLettersJasperDto.getUserInput09());
			statementsRemarksList.set(26, statements);
			
			statements =  new AuditLettersStatementsJasperDto();
			statements.setSrNo("28");
			statements.setStatementsRemarks(auditLettersJasperDto.getUserInput10());
			statementsRemarksList.set(27, statements);
			
			statements =  new AuditLettersStatementsJasperDto();
			statements.setSrNo("33");
			statements.setStatementsRemarks(auditLettersJasperDto.getUserInput11());
			statementsRemarksList.set(32, statements);
			
			statements =  new AuditLettersStatementsJasperDto();
			statements.setSrNo("34");
			statements.setStatementsRemarks(auditLettersJasperDto.getUserInput12());
			statementsRemarksList.set(33, statements);
			
			statements =  new AuditLettersStatementsJasperDto();
			statements.setSrNo("35");
			statements.setStatementsRemarks(auditLettersJasperDto.getUserInput13());
			statementsRemarksList.set(34, statements);				
		
		}else if(letterCode.equalsIgnoreCase(BankAuditConstant.LETTER_CODE_HoR)  || letterCode.equalsIgnoreCase(BankAuditConstant.LETTER_CODE_RoR)){
			for (int len=0 ;  len<stmtKeys.length ; len++) {
				
				AuditLettersStatementsJasperDto statements =  new AuditLettersStatementsJasperDto();				 
				statements.setSrNo(stmtKeys[len]); 
				String userInput = "userInput"+String.format("%02d", (80-len) );				 
				Object userInputObject = org.apache.commons.beanutils.PropertyUtils.getSimpleProperty(auditLettersJasperDto, userInput);
				if(userInputObject!=null && !"".equals(userInputObject.toString())){
					statements.setStatementsRemarks(userInputObject.toString());  
				} 
				statementsRemarksList.add(statements);	
								
				/***************** START OLD CODE ****************	
				AuditObservationLetterDto auditObservationLetterDto = chklstDrvStmntMap.get(seqNo);
				if(auditObservationLetterDto!=null){
					if(seqNo.equalsIgnoreCase("II") || seqNo.equalsIgnoreCase("VI") || seqNo.equalsIgnoreCase("VII") 
							|| seqNo.equalsIgnoreCase("IX") || seqNo.equalsIgnoreCase("XI")
							|| seqNo.equalsIgnoreCase("XII") || seqNo.equalsIgnoreCase("XVI") ||seqNo.equalsIgnoreCase("XIX")
							|| seqNo.equalsIgnoreCase("XX") || seqNo.equalsIgnoreCase("XXI") || seqNo.equalsIgnoreCase("XXII")
							|| seqNo.equalsIgnoreCase("XXIII") || seqNo.equalsIgnoreCase("XXIV") || seqNo.equalsIgnoreCase("XXVI")){
					//if(BankAuditUtil.isEmptyString(auditObservationLetterDto.getDerivedStatement())){
						if(BankAuditConstant.COMPLIANCE_YES.equalsIgnoreCase(auditObservationLetterDto.getComplianceCategory()) 
								&& !BankAuditConstant.NO.equalsIgnoreCase(auditObservationLetterDto.getStandardStmntCompliancePrint())){
						
							String standardStmt1=auditObservationLetterDto.getStandardStmntCompliance()==null?"":auditObservationLetterDto.getStandardStmntCompliance()+"<br/>";								
							String standardStmt2=auditObservationLetterDto.getFindingRemarks()==null?"":auditObservationLetterDto.getFindingRemarks() ;
							statements.setStatementsRemarks(standardStmt1+""+standardStmt2);					
						
						}else if(BankAuditConstant.COMPLIANCE_NO.equalsIgnoreCase(auditObservationLetterDto.getComplianceCategory()) 
								&& !BankAuditConstant.NO.equalsIgnoreCase(auditObservationLetterDto.getStandardStmntNonCompliancePrint())){
							
							String standardStmt1=auditObservationLetterDto.getStandardStmntNonCompliance()==null?"":auditObservationLetterDto.getStandardStmntNonCompliance()+"<br/>";
							String standardStmt2=auditObservationLetterDto.getFindingRemarks()==null?"":auditObservationLetterDto.getFindingRemarks() ;								
							statements.setStatementsRemarks(standardStmt1+ "" + standardStmt2);					
							//statements.setStatementsRemarks( auditObservationLetterDto.getFindingRemarks());
						}
					}else{
						statements.setStatementsRemarks(auditObservationLetterDto.getDerivedStatement());
					}						 
				}	
				statementsRemarksList.add(statements);
				***************** END OLD CODE ****************/				
			}
			
			AuditLettersStatementsJasperDto statements =  new AuditLettersStatementsJasperDto();			
			statements.setSrNo("27");
			statements.setStatementsRemarks(auditLettersJasperDto.getUserInput01());  
			statementsRemarksList.set(26, statements);	
		}			
		
		//Remove sequence number if no statement and update 
		int sequenceNumber = 0;
		List<AuditLettersStatementsJasperDto> statementsRemarksListUpdated = new ArrayList<AuditLettersStatementsJasperDto>();
		for (AuditLettersStatementsJasperDto auditLettersStatementsJasperDto : statementsRemarksList) {
			String statement = auditLettersStatementsJasperDto.getStatementsRemarks();
			if(!BankAuditUtil.isEmptyString(statement)){
				statement = statement.replaceAll("(\r\n|\n\r|\n|\r)", "<br>");
				auditLettersStatementsJasperDto.setStatementsRemarks(statement);
				auditLettersStatementsJasperDto.setSrNo(stmtKeys[sequenceNumber]);
				statementsRemarksListUpdated.add(auditLettersStatementsJasperDto);
				sequenceNumber++;
			}
		}			
		
		if(letterCode.equalsIgnoreCase(BankAuditConstant.LETTER_CODE_HoR)  || letterCode.equalsIgnoreCase(BankAuditConstant.LETTER_CODE_RoR)) {
			AuditObservationLetterDto statement2 = chklstDrvStmntMap.get("2.1");
			AuditObservationLetterDto statement3 = chklstDrvStmntMap.get("3.1");
			if(statement2!=null){
				if(BankAuditConstant.COMPLIANCE_YES.equalsIgnoreCase(statement2.getComplianceCategory()) 
						&& !BankAuditConstant.NO.equalsIgnoreCase(statement2.getStandardStmntCompliancePrint())){
					
					String stmt1 = statement2.getStandardStmntCompliance()==null?"":(statement2.getStandardStmntCompliance()+"<br/>");
					String stmt2 = statement2.getFindingRemarks()==null?"":(statement2.getFindingRemarks());
					auditLettersJasperDto.setStatement2(stmt1+""+stmt2);

				}else if(BankAuditConstant.COMPLIANCE_NO.equalsIgnoreCase(statement2.getComplianceCategory()) 
						&& !BankAuditConstant.NO.equalsIgnoreCase(statement2.getStandardStmntNonCompliancePrint())){
					
					String stmt1 = statement2.getStandardStmntNonCompliance()==null?"":(statement2.getStandardStmntNonCompliance()+"<br/>");
					String stmt2 = statement2.getFindingRemarks()==null?"":(statement2.getFindingRemarks());
					auditLettersJasperDto.setStatement2(stmt1+""+stmt2);
					
				}
			}
			if(statement3!=null){
				if(BankAuditConstant.COMPLIANCE_YES.equalsIgnoreCase(statement3.getComplianceCategory()) 
						&& !BankAuditConstant.NO.equalsIgnoreCase(statement3.getStandardStmntCompliancePrint())){
					
					String stmt1 = statement3.getStandardStmntCompliance()==null?"":(statement3.getStandardStmntCompliance()+"<br/>");
					String stmt2 = statement3.getFindingRemarks()==null?"":(statement3.getFindingRemarks());
					auditLettersJasperDto.setStatement3(stmt1+""+stmt2);				
					
				}else if(BankAuditConstant.COMPLIANCE_NO.equalsIgnoreCase(statement3.getComplianceCategory()) 
						&& !BankAuditConstant.NO.equalsIgnoreCase(statement3.getStandardStmntNonCompliancePrint())){
					
					String stmt1 = statement3.getStandardStmntNonCompliance()==null?"":(statement3.getStandardStmntNonCompliance()+"<br/>");
					String stmt2 = statement3.getFindingRemarks()==null?"":(statement3.getFindingRemarks());
					auditLettersJasperDto.setStatement3(stmt1+""+stmt2);
					
				}
			}
		}else if(letterCode.equalsIgnoreCase(BankAuditConstant.LETTER_CODE_RN)){
			
			auditLettersJasperDto.setStatementRN_15_1("");	
			auditLettersJasperDto.setStatementRN_10_2("");
			auditLettersJasperDto.setStatementRN_10_3("");
			
			/*AuditObservationLetterDto statementRN_15_1 = chklstDrvStmntMap.get("15.1");				
			if(statementRN_15_1!=null){
				if(BankAuditConstant.COMPLIANCE_YES.equalsIgnoreCase(statementRN_15_1.getComplianceCategory()) 
						&& !BankAuditConstant.NO.equalsIgnoreCase(statementRN_15_1.getStandardStmntCompliancePrint())){
					
					String stmt1 = statementRN_15_1.getStandardStmntCompliance()==null?"":(statementRN_15_1.getStandardStmntCompliance()+"<br/>");
					String stmt2 = statementRN_15_1.getFindingRemarks()==null?"":(statementRN_15_1.getFindingRemarks());
					auditLettersJasperDto.setStatementRN_15_1(stmt1+""+stmt2);		
					
				}else if(BankAuditConstant.COMPLIANCE_NO.equalsIgnoreCase(statementRN_15_1.getComplianceCategory()) 
						&& !BankAuditConstant.NO.equalsIgnoreCase(statementRN_15_1.getStandardStmntNonCompliancePrint())){	
					
					String stmt1 = statementRN_15_1.getStandardStmntNonCompliance()==null?"":(statementRN_15_1.getStandardStmntNonCompliance()+"<br/>");
					String stmt2 = statementRN_15_1.getFindingRemarks()==null?"":(statementRN_15_1.getFindingRemarks());
					auditLettersJasperDto.setStatementRN_15_1(stmt1+""+stmt2);					
				}
			}*/
			
			auditLettersJasperDto.setStatementRN_15_1(auditLettersJasperDto.getUserInput39());
			
			AuditObservationLetterDto statementRN_10_2 = chklstDrvStmntMap.get("10.2");	
			AuditObservationLetterDto statementRN_10_3 = chklstDrvStmntMap.get("10.3");	
			if(statementRN_10_2!=null){
				auditLettersJasperDto.setStatementRN_10_2(statementRN_10_2.getComplianceCategory());
			}
			if(statementRN_10_3!=null){
				auditLettersJasperDto.setStatementRN_10_3(statementRN_10_3.getComplianceCategory());
			}							
			
			AuditObservationLetterDto statementRN_10_1_X = chklstDrvStmntMap.get("10.1.X");
			if(statementRN_10_1_X!=null){
				parameterChklstDrvStmntMap.put("statementDrv_10.1.X", statementRN_10_1_X.getDerivedStatement());
			}
			
			//update supervisoryRating score from audit_schedule table
			parameterMap.put("3BOM-653", auditRating.getSupervisoryRiskPrcntg());  //Rating,  
			parameterMap.put("3BOM-652", auditRating.getSupervisoryRating()); //category,  
			
		}
		//auditLettersJasperDto.setStatementsRemarksList(statementsRemarksList);
		auditLettersJasperDto.setStatementsRemarksList(statementsRemarksListUpdated);
		auditLettersJasperDto.setParameterChklstDrvStmntMap(parameterChklstDrvStmntMap);			
		auditLettersJasperDto.setParameterMap(parameterMap);
				
		return auditLettersJasperDto;
	}
	
	private AuditLettersJasperDto processDCCBLetters(String letterCode,int legalEntityCode, String auditId,
			AuditLettersJasperDto auditLettersJasperDto, Map<String, AuditObservationLetterDto> chklstDrvStmntMap,
			 String[] stmtKeys, AuditRating auditRating, AuditSchedule auditSchedulePre) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException{
		
		List<AuditLettersStatementsJasperDto> statementsRemarksList = new ArrayList<AuditLettersStatementsJasperDto>();	
		Map<String, String> parameterChklstDrvStmntMap =  new HashMap<String, String>();
		Map<String, String> parameterMap = interfaceParameterService.getProfileDetailsByAuditId(legalEntityCode, auditId, null);		
		
		/***** Add Desk and Field/Onsite compliance rating ********/
		if(auditSchedulePre != null){
			parameterMap.put("complianceScoreDesk", auditSchedulePre.getDeskComplianceScore());
			parameterMap.put("complianceCategoryDesk", auditSchedulePre.getDeskComplianceRating());
			parameterMap.put("complianceScoreField", auditSchedulePre.getOnsiteComplianceScore());			
			parameterMap.put("complianceCategoryField", auditSchedulePre.getOnsiteComplianceRating());
		}
		if(letterCode.contains("LoSC")){
			for (int len=0; len<stmtKeys.length; len++) {
				  
				AuditLettersStatementsJasperDto statements =  new AuditLettersStatementsJasperDto();				 
				statements.setSrNo(stmtKeys[len]); 
				String userInput = "userInput"+String.format("%02d", (80-len) );				 
				Object userInputObject = org.apache.commons.beanutils.PropertyUtils.getSimpleProperty(auditLettersJasperDto, userInput);
				if(userInput.equalsIgnoreCase("userInput50")){
					System.out.println("==============");
				}
				if(userInputObject!=null && !"".equals(userInputObject.toString())){
					statements.setStatementsRemarks(userInputObject.toString()); 
				}  
				statementsRemarksList.add(statements);					
				
				/***************** START OLD CODE ****************	
				AuditObservationLetterDto auditObservationLetterDto = chklstDrvStmntMap.get(seqNo);
				if(auditObservationLetterDto!=null){
					
					if(seqNo.equalsIgnoreCase("4") || seqNo.equalsIgnoreCase("5") || seqNo.equalsIgnoreCase("7") 
							|| seqNo.equalsIgnoreCase("10") || seqNo.equalsIgnoreCase("11") || seqNo.equalsIgnoreCase("12")
							|| seqNo.equalsIgnoreCase("13") || seqNo.equalsIgnoreCase("14") || seqNo.equalsIgnoreCase("18") 
							|| seqNo.equalsIgnoreCase("21") || seqNo.equalsIgnoreCase("22") || seqNo.equalsIgnoreCase("23") 
							|| seqNo.equalsIgnoreCase("24") || seqNo.equalsIgnoreCase("25")){
					//if(BankAuditUtil.isEmptyString(auditObservationLetterDto.getDerivedStatement())){
						if(BankAuditConstant.COMPLIANCE_YES.equalsIgnoreCase(auditObservationLetterDto.getComplianceCategory()) 
								&& !BankAuditConstant.NO.equalsIgnoreCase(auditObservationLetterDto.getStandardStmntCompliancePrint())){
							// if Compliance no print
							//statements.setStatementsRemarks(auditObservationLetterDto.getStandardStmntCompliance());					
						}else if(BankAuditConstant.COMPLIANCE_NO.equalsIgnoreCase(auditObservationLetterDto.getComplianceCategory()) 
								&& !BankAuditConstant.NO.equalsIgnoreCase(auditObservationLetterDto.getStandardStmntNonCompliancePrint())){
							
							String standardStmt1=auditObservationLetterDto.getStandardStmntNonCompliance()==null?"":auditObservationLetterDto.getStandardStmntNonCompliance()+"<br/>";
							String standardStmt2=auditObservationLetterDto.getFindingRemarks()==null?"":auditObservationLetterDto.getFindingRemarks();
							statements.setStatementsRemarks(standardStmt1+ "" + standardStmt2);			
							//statements.setStatementsRemarks(auditObservationLetterDto.getFindingRemarks());
							
						}
					}else{
						if(auditObservationLetterDto.isDerivedStatementIsNegetive()){
							statements.setStatementsRemarks(auditObservationLetterDto.getDerivedStatement());
						}
					}						 
				}	
				statementsRemarksList.add(statements);
				***************** END OLD CODE ****************/
			}
			
			AuditLettersStatementsJasperDto statements =  new AuditLettersStatementsJasperDto();
			
			statements.setSrNo("32");
			statements.setStatementsRemarks(auditLettersJasperDto.getUserInput08());  
			statementsRemarksList.add(31, statements);
			
			statements =  new AuditLettersStatementsJasperDto();
			statements.setSrNo("33");
			statements.setStatementsRemarks(auditLettersJasperDto.getUserInput09());
			statementsRemarksList.add(32, statements);
			
			statements =  new AuditLettersStatementsJasperDto();
			statements.setSrNo("34");
			statements.setStatementsRemarks(auditLettersJasperDto.getUserInput10());
			statementsRemarksList.add(33, statements);
			
			statements =  new AuditLettersStatementsJasperDto();
			statements.setSrNo("38");
			statements.setStatementsRemarks(auditLettersJasperDto.getUserInput11());
			statementsRemarksList.add(37, statements);
			
			statements =  new AuditLettersStatementsJasperDto();
			statements.setSrNo("39");
			statements.setStatementsRemarks(auditLettersJasperDto.getUserInput12());
			statementsRemarksList.add(38, statements);
			
			statements =  new AuditLettersStatementsJasperDto();
			statements.setSrNo("40");
			statements.setStatementsRemarks(auditLettersJasperDto.getUserInput13());
			statementsRemarksList.add(39, statements);			
			
			statements =  new AuditLettersStatementsJasperDto();
			statements.setSrNo("41");
			statements.setStatementsRemarks(auditLettersJasperDto.getUserInput14());
			statementsRemarksList.add(40, statements);			
		
		}else if(letterCode.equalsIgnoreCase(BankAuditConstant.LETTER_CODE_HoR)  || letterCode.equalsIgnoreCase(BankAuditConstant.LETTER_CODE_RoR)){
			for (int len=0; len<stmtKeys.length; len++) {
				  
				AuditLettersStatementsJasperDto statements =  new AuditLettersStatementsJasperDto();				 
				statements.setSrNo(stmtKeys[len]); 
				String userInput = "userInput"+String.format("%02d", (80-len) );				 
				Object userInputObject = org.apache.commons.beanutils.PropertyUtils.getSimpleProperty(auditLettersJasperDto, userInput);
				if(userInputObject!=null && !"".equals(userInputObject.toString())){
					statements.setStatementsRemarks(userInputObject.toString()); 
				}  
				statementsRemarksList.add(statements);					
				
				/***************** START OLD CODE ****************				
				AuditObservationLetterDto auditObservationLetterDto = chklstDrvStmntMap.get(seqNo);
				if(auditObservationLetterDto!=null){
					if(seqNo.equalsIgnoreCase("VI") || seqNo.equalsIgnoreCase("VII") || seqNo.equalsIgnoreCase("IX")  
							|| seqNo.equalsIgnoreCase("XII")   || seqNo.equalsIgnoreCase("XIII")    || seqNo.equalsIgnoreCase("XVI")
							|| seqNo.equalsIgnoreCase("XVII")  ||seqNo.equalsIgnoreCase("XXII")     || seqNo.equalsIgnoreCase("XXIII")
							|| seqNo.equalsIgnoreCase("XXIV")  || seqNo.equalsIgnoreCase("XXV")     || seqNo.equalsIgnoreCase("XXVI")
							|| seqNo.equalsIgnoreCase("XXVII") || seqNo.equalsIgnoreCase("XXVIII")	|| seqNo.equalsIgnoreCase("XXIX")
							|| seqNo.equalsIgnoreCase("XXX")   || seqNo.equalsIgnoreCase("XXXI") 
							)
					{
					//if(BankAuditUtil.isEmptyString(auditObservationLetterDto.getDerivedStatement())){
						if(BankAuditConstant.COMPLIANCE_YES.equalsIgnoreCase(auditObservationLetterDto.getComplianceCategory()) 
								&& !BankAuditConstant.NO.equalsIgnoreCase(auditObservationLetterDto.getStandardStmntCompliancePrint())){
						
							String standardStmt1=auditObservationLetterDto.getStandardStmntCompliance()==null?"":auditObservationLetterDto.getStandardStmntCompliance()+"<br/>";								
							String standardStmt2=auditObservationLetterDto.getFindingRemarks()==null?"":auditObservationLetterDto.getFindingRemarks() ;
							statements.setStatementsRemarks(standardStmt1+""+standardStmt2);					
						
						}else if(BankAuditConstant.COMPLIANCE_NO.equalsIgnoreCase(auditObservationLetterDto.getComplianceCategory()) 
								&& !BankAuditConstant.NO.equalsIgnoreCase(auditObservationLetterDto.getStandardStmntNonCompliancePrint())){
							
							String standardStmt1=auditObservationLetterDto.getStandardStmntNonCompliance()==null?"":auditObservationLetterDto.getStandardStmntNonCompliance()+"<br/>";
							String standardStmt2=auditObservationLetterDto.getFindingRemarks()==null?"":auditObservationLetterDto.getFindingRemarks() ;								
							statements.setStatementsRemarks(standardStmt1+ "" + standardStmt2);					
							//statements.setStatementsRemarks( auditObservationLetterDto.getFindingRemarks());
						}
					}else{
						statements.setStatementsRemarks(auditObservationLetterDto.getDerivedStatement());
					}						 
				}	
				statementsRemarksList.add(statements);
				***************** END OLD CODE ****************/
			}
			
			AuditLettersStatementsJasperDto statements =  new AuditLettersStatementsJasperDto();
			
			statements.setSrNo("37");
			statements.setStatementsRemarks(auditLettersJasperDto.getUserInput01());  
			statementsRemarksList.set(36, statements);
			
			statements =  new AuditLettersStatementsJasperDto();
			statements.setSrNo("38");
			statements.setStatementsRemarks(auditLettersJasperDto.getUserInput02());  
			statementsRemarksList.set(37, statements);
		}			
		
		//Remove sequence number if no statement and update 
		int sequenceNumber = 0;
		List<AuditLettersStatementsJasperDto> statementsRemarksListUpdated = new ArrayList<AuditLettersStatementsJasperDto>();
		for (AuditLettersStatementsJasperDto auditLettersStatementsJasperDto : statementsRemarksList) {
			String statement = auditLettersStatementsJasperDto.getStatementsRemarks();
			if(!BankAuditUtil.isEmptyString(statement)){
				statement = statement.replaceAll("(\r\n|\n\r|\n|\r)", "<br>");
				auditLettersStatementsJasperDto.setStatementsRemarks(statement);
				auditLettersStatementsJasperDto.setSrNo(stmtKeys[sequenceNumber]);
				statementsRemarksListUpdated.add(auditLettersStatementsJasperDto);
				sequenceNumber++;
			}
		}			
		
		if(letterCode.equalsIgnoreCase(BankAuditConstant.LETTER_CODE_HoR)  || letterCode.equalsIgnoreCase(BankAuditConstant.LETTER_CODE_RoR)) {
			AuditObservationLetterDto statement2 = chklstDrvStmntMap.get("2.1");			 
			if(statement2!=null){
				if(BankAuditConstant.COMPLIANCE_YES.equalsIgnoreCase(statement2.getComplianceCategory()) 
						&& !BankAuditConstant.NO.equalsIgnoreCase(statement2.getStandardStmntCompliancePrint())){
					
					String stmt1 = statement2.getStandardStmntCompliance()==null?"":(statement2.getStandardStmntCompliance()+"<br/>");
					String stmt2 = statement2.getFindingRemarks()==null?"":(statement2.getFindingRemarks());
					auditLettersJasperDto.setStatement2(stmt1+""+stmt2);
					parameterChklstDrvStmntMap.put("statement2", stmt1+""+stmt2);

				}else if(BankAuditConstant.COMPLIANCE_NO.equalsIgnoreCase(statement2.getComplianceCategory()) 
						&& !BankAuditConstant.NO.equalsIgnoreCase(statement2.getStandardStmntNonCompliancePrint())){
					
					String stmt1 = statement2.getStandardStmntNonCompliance()==null?"":(statement2.getStandardStmntNonCompliance()+"<br/>");
					String stmt2 = statement2.getFindingRemarks()==null?"":(statement2.getFindingRemarks());
					auditLettersJasperDto.setStatement2(stmt1+""+stmt2);
					parameterChklstDrvStmntMap.put("statement2", stmt1+""+stmt2);
					
				}
			} 
		}else if(letterCode.equalsIgnoreCase(BankAuditConstant.LETTER_CODE_RN)){
						
			/*AuditObservationLetterDto statementRN_6_1_3 = chklstDrvStmntMap.get("6.1.3");	
			AuditObservationLetterDto statementRN_6_1_4 = chklstDrvStmntMap.get("6.1.4");	
			AuditObservationLetterDto statementRN_6_1_5 = chklstDrvStmntMap.get("6.1.5");	
			AuditObservationLetterDto statementRN_6_1_6 = chklstDrvStmntMap.get("6.1.6");
			AuditObservationLetterDto statementRN_6_4_2 = chklstDrvStmntMap.get("6.4.2");
			AuditObservationLetterDto statementRN_6_5_2 = chklstDrvStmntMap.get("6.5.2");
			AuditObservationLetterDto statementRN_6_6_2 = chklstDrvStmntMap.get("6.6.2");
			
			if(statementRN_6_1_3!=null){ 
				parameterChklstDrvStmntMap.put("6.1.3",statementRN_6_1_3.getComplianceCategory());
			}
			if(statementRN_6_1_4!=null){ 
				parameterChklstDrvStmntMap.put("6.1.4",statementRN_6_1_4.getComplianceCategory());
			}
			if(statementRN_6_1_5!=null){  
				parameterChklstDrvStmntMap.put("6.1.5",statementRN_6_1_5.getComplianceCategory());
			}
			if(statementRN_6_1_6!=null){ 
				parameterChklstDrvStmntMap.put("6.1.6",statementRN_6_1_6.getComplianceCategory());
			}			
			if(statementRN_6_4_2!=null){ 
				parameterChklstDrvStmntMap.put("6.4.2",statementRN_6_4_2.getComplianceCategory());
			}
			if(statementRN_6_5_2!=null){ 
				parameterChklstDrvStmntMap.put("6.5.2",statementRN_6_5_2.getComplianceCategory());
			}
			if(statementRN_6_6_2!=null){ 
				parameterChklstDrvStmntMap.put("6.6.2",statementRN_6_6_2.getComplianceCategory());
			}*/
			AuditObservationLetterDto statementRN_11_1_X = chklstDrvStmntMap.get("11.1.X");
			if(statementRN_11_1_X!=null){
				parameterChklstDrvStmntMap.put("statementDrv_11.1.X", statementRN_11_1_X.getDerivedStatement());
			}
			
			//update supervisoryRating score from audit_schedule table
			parameterMap.put("3BOMD637", auditRating.getSupervisoryRiskPrcntg());  //Rating 
			parameterMap.put("3BOMD638", auditRating.getSupervisoryRating()); //category
			 
		}

		auditLettersJasperDto.setStatementsRemarksList(statementsRemarksListUpdated);		
		auditLettersJasperDto.setParameterMap(parameterMap);
		auditLettersJasperDto.setDliDpiParamMap(interfaceParameterService.getDliDpiDetailsByAuditId(legalEntityCode, auditId, null));
		auditLettersJasperDto.setParameterChklstDrvStmntMap(parameterChklstDrvStmntMap);
		return auditLettersJasperDto;
	}
	
	private AuditLettersJasperDto processStCBLetters(String letterCode,int legalEntityCode, String auditId,
			AuditLettersJasperDto auditLettersJasperDto, Map<String, AuditObservationLetterDto> chklstDrvStmntMap,
			 String[] stmtKeys, AuditRating auditRating, AuditSchedule auditSchedulePre) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException{
		
		List<AuditLettersStatementsJasperDto> statementsRemarksList = new ArrayList<AuditLettersStatementsJasperDto>();	
		Map<String, String> parameterChklstDrvStmntMap =  new HashMap<String, String>();
		if(letterCode.contains("LoSC")){
			for (int len=0; len<stmtKeys.length; len++) {
				  
				AuditLettersStatementsJasperDto statements =  new AuditLettersStatementsJasperDto();				 
				statements.setSrNo(stmtKeys[len]); 
				String userInput = "userInput"+String.format("%02d", (80-len) );				 
				Object userInputObject = org.apache.commons.beanutils.PropertyUtils.getSimpleProperty(auditLettersJasperDto, userInput);
				if(userInputObject!=null && !"".equals(userInputObject.toString())){
					statements.setStatementsRemarks(userInputObject.toString());  										
				} 
				statementsRemarksList.add(statements);
				
				/***************** START OLD CODE ****************				
				AuditObservationLetterDto auditObservationLetterDto = chklstDrvStmntMap.get(seqNo);
				if(auditObservationLetterDto!=null){
					
					if(seqNo.equalsIgnoreCase("4") || seqNo.equalsIgnoreCase("5") || seqNo.equalsIgnoreCase("6")	
							|| seqNo.equalsIgnoreCase("8") 	|| seqNo.equalsIgnoreCase("11") || seqNo.equalsIgnoreCase("12")
							|| seqNo.equalsIgnoreCase("13") || seqNo.equalsIgnoreCase("14") || seqNo.equalsIgnoreCase("15") 
							|| seqNo.equalsIgnoreCase("16") || seqNo.equalsIgnoreCase("20") || seqNo.equalsIgnoreCase("23") 
							|| seqNo.equalsIgnoreCase("24") || seqNo.equalsIgnoreCase("25")	|| seqNo.equalsIgnoreCase("26") 
							|| seqNo.equalsIgnoreCase("27")){
					//if(BankAuditUtil.isEmptyString(auditObservationLetterDto.getDerivedStatement())){
						if(BankAuditConstant.COMPLIANCE_YES.equalsIgnoreCase(auditObservationLetterDto.getComplianceCategory()) 
								&& !BankAuditConstant.NO.equalsIgnoreCase(auditObservationLetterDto.getStandardStmntCompliancePrint())){
							// if Compliance no print
							//statements.setStatementsRemarks(auditObservationLetterDto.getStandardStmntCompliance());					
						}else if(BankAuditConstant.COMPLIANCE_NO.equalsIgnoreCase(auditObservationLetterDto.getComplianceCategory()) 
								&& !BankAuditConstant.NO.equalsIgnoreCase(auditObservationLetterDto.getStandardStmntNonCompliancePrint())){
							
							String standardStmt1=auditObservationLetterDto.getStandardStmntNonCompliance()==null?"":auditObservationLetterDto.getStandardStmntNonCompliance()+"<br/>";
							String standardStmt2=auditObservationLetterDto.getFindingRemarks()==null?"":auditObservationLetterDto.getFindingRemarks();
							statements.setStatementsRemarks(standardStmt1+ "" + standardStmt2);			
							//statements.setStatementsRemarks(auditObservationLetterDto.getFindingRemarks());
							
						}
					}else{
						if(auditObservationLetterDto.isDerivedStatementIsNegetive()){
							statements.setStatementsRemarks(auditObservationLetterDto.getDerivedStatement());
						}
					}						 
				}	
				statementsRemarksList.add(statements);
				***************** END OLD CODE ****************/
			}
			
			AuditLettersStatementsJasperDto statements =  new AuditLettersStatementsJasperDto();
			
			statements.setSrNo("34");
			statements.setStatementsRemarks(auditLettersJasperDto.getUserInput08());  
			statementsRemarksList.add(33, statements);
			
			statements =  new AuditLettersStatementsJasperDto();
			statements.setSrNo("35");
			statements.setStatementsRemarks(auditLettersJasperDto.getUserInput09());
			statementsRemarksList.add(34, statements);
			
			statements =  new AuditLettersStatementsJasperDto();
			statements.setSrNo("36");
			statements.setStatementsRemarks(auditLettersJasperDto.getUserInput10());
			statementsRemarksList.add(35, statements);
			
			statements =  new AuditLettersStatementsJasperDto();
			statements.setSrNo("40");
			statements.setStatementsRemarks(auditLettersJasperDto.getUserInput11());
			statementsRemarksList.add(39, statements);
			
			statements =  new AuditLettersStatementsJasperDto();
			statements.setSrNo("41");
			statements.setStatementsRemarks(auditLettersJasperDto.getUserInput12());
			statementsRemarksList.add(40, statements);
			
			statements =  new AuditLettersStatementsJasperDto();
			statements.setSrNo("42");
			statements.setStatementsRemarks(auditLettersJasperDto.getUserInput13());
			statementsRemarksList.add(41, statements);				
		
			statements =  new AuditLettersStatementsJasperDto();
			statements.setSrNo("43");
			statements.setStatementsRemarks(auditLettersJasperDto.getUserInput14());
			statementsRemarksList.add(42, statements);				
		
			
		}else if(letterCode.equalsIgnoreCase(BankAuditConstant.LETTER_CODE_HoR)  || letterCode.equalsIgnoreCase(BankAuditConstant.LETTER_CODE_RoR)){
			for (int len=0; len<stmtKeys.length; len++) {
				  
				AuditLettersStatementsJasperDto statements =  new AuditLettersStatementsJasperDto();				 
				statements.setSrNo(stmtKeys[len]); 
				String userInput = "userInput"+String.format("%02d", (80-len) );				 
				Object userInputObject = org.apache.commons.beanutils.PropertyUtils.getSimpleProperty(auditLettersJasperDto, userInput);
				if(userInputObject!=null && !"".equals(userInputObject.toString())){
					statements.setStatementsRemarks(userInputObject.toString());  
				} 
				statementsRemarksList.add(statements);
				
				/***************** START OLD CODE ****************
				AuditObservationLetterDto auditObservationLetterDto = chklstDrvStmntMap.get(seqNo);
				if(auditObservationLetterDto!=null){
					if(seqNo.equalsIgnoreCase("VI") || seqNo.equalsIgnoreCase("VII") || seqNo.equalsIgnoreCase("XIII")  
							|| seqNo.equalsIgnoreCase("X")		|| seqNo.equalsIgnoreCase("XI")	  || seqNo.equalsIgnoreCase("XII") 							
							|| seqNo.equalsIgnoreCase("XV") 	|| seqNo.equalsIgnoreCase("XVI")  || seqNo.equalsIgnoreCase("XIX")  
							||seqNo.equalsIgnoreCase("XX")		|| seqNo.equalsIgnoreCase("XXIV")|| seqNo.equalsIgnoreCase("XXVI")							
							|| seqNo.equalsIgnoreCase("XXVII") 	|| seqNo.equalsIgnoreCase("XXVIII")	|| seqNo.equalsIgnoreCase("XXIX")
							|| seqNo.equalsIgnoreCase("XXX")  	|| seqNo.equalsIgnoreCase("XXXI") 	|| seqNo.equalsIgnoreCase("XXXII") 
							|| seqNo.equalsIgnoreCase("XXXIII") || seqNo.equalsIgnoreCase("XXXIV") 	|| seqNo.equalsIgnoreCase("XXXV") )
					{
					//if(BankAuditUtil.isEmptyString(auditObservationLetterDto.getDerivedStatement())){
						if(BankAuditConstant.COMPLIANCE_YES.equalsIgnoreCase(auditObservationLetterDto.getComplianceCategory()) 
								&& !BankAuditConstant.NO.equalsIgnoreCase(auditObservationLetterDto.getStandardStmntCompliancePrint())){
						
							String standardStmt1=auditObservationLetterDto.getStandardStmntCompliance()==null?"":auditObservationLetterDto.getStandardStmntCompliance()+"<br/>";								
							String standardStmt2=auditObservationLetterDto.getFindingRemarks()==null?"":auditObservationLetterDto.getFindingRemarks() ;
							statements.setStatementsRemarks(standardStmt1+""+standardStmt2);					
						
						}else if(BankAuditConstant.COMPLIANCE_NO.equalsIgnoreCase(auditObservationLetterDto.getComplianceCategory()) 
								&& !BankAuditConstant.NO.equalsIgnoreCase(auditObservationLetterDto.getStandardStmntNonCompliancePrint())){
							
							String standardStmt1=auditObservationLetterDto.getStandardStmntNonCompliance()==null?"":auditObservationLetterDto.getStandardStmntNonCompliance()+"<br/>";
							String standardStmt2=auditObservationLetterDto.getFindingRemarks()==null?"":auditObservationLetterDto.getFindingRemarks() ;								
							statements.setStatementsRemarks(standardStmt1+ "" + standardStmt2);					
							//statements.setStatementsRemarks( auditObservationLetterDto.getFindingRemarks());
						}
					}else{
						statements.setStatementsRemarks(auditObservationLetterDto.getDerivedStatement());
					}						 
				}	
				statementsRemarksList.add(statements);
				***************** END OLD CODE ****************/
			}
			
			AuditLettersStatementsJasperDto statements =  new AuditLettersStatementsJasperDto();
			
			statements.setSrNo("39");
			statements.setStatementsRemarks(auditLettersJasperDto.getUserInput01());  
			statementsRemarksList.set(38, statements);
			
			statements =  new AuditLettersStatementsJasperDto();
			statements.setSrNo("40");
			statements.setStatementsRemarks(auditLettersJasperDto.getUserInput02());  
			statementsRemarksList.set(39, statements);
		}			
		
		//Remove sequence number if no statement and update 
		int sequenceNumber = 0;
		List<AuditLettersStatementsJasperDto> statementsRemarksListUpdated = new ArrayList<AuditLettersStatementsJasperDto>();
		for (AuditLettersStatementsJasperDto auditLettersStatementsJasperDto : statementsRemarksList) {
			String statement = auditLettersStatementsJasperDto.getStatementsRemarks();
			if(!BankAuditUtil.isEmptyString(statement)){
				statement = statement.replaceAll("(\r\n|\n\r|\n|\r)", "<br>");
				auditLettersStatementsJasperDto.setStatementsRemarks(statement);
				auditLettersStatementsJasperDto.setSrNo(stmtKeys[sequenceNumber]);
				statementsRemarksListUpdated.add(auditLettersStatementsJasperDto);
				sequenceNumber++;
			}
		}			
		 
		Map<String, String> parameterMap = interfaceParameterService.getProfileDetailsByAuditId(legalEntityCode, auditId, null); 
		/***** Add Desk and Field/Onsite compliance rating ********/
		if(auditSchedulePre !=null ){
			parameterMap.put("complianceScoreDesk", auditSchedulePre.getDeskComplianceScore());
			parameterMap.put("complianceCategoryDesk", auditSchedulePre.getDeskComplianceRating());
			parameterMap.put("complianceScoreField", auditSchedulePre.getOnsiteComplianceScore());			
			parameterMap.put("complianceCategoryField", auditSchedulePre.getOnsiteComplianceRating());
		}
		
		if(letterCode.equalsIgnoreCase(BankAuditConstant.LETTER_CODE_HoR)  || letterCode.equalsIgnoreCase(BankAuditConstant.LETTER_CODE_RoR)) { 
			AuditObservationLetterDto statement2 = chklstDrvStmntMap.get("2.5.10.1.1");
			String BOMS602 = parameterMap.get("3BOMS602");
			if(BOMS602!=null && (BOMS602.equalsIgnoreCase("NO") || BOMS602.equalsIgnoreCase("0"))){
				statement2 = chklstDrvStmntMap.get("2.5.9.1.1");
			}
			
			if(statement2!=null){
				if(BankAuditConstant.COMPLIANCE_YES.equalsIgnoreCase(statement2.getComplianceCategory()) 
						&& !BankAuditConstant.NO.equalsIgnoreCase(statement2.getStandardStmntCompliancePrint())){
					
					String stmt1 = statement2.getStandardStmntCompliance()==null?"":(statement2.getStandardStmntCompliance()+"<br/>");
					String stmt2 = statement2.getFindingRemarks()==null?"":(statement2.getFindingRemarks());
					auditLettersJasperDto.setStatement2(stmt1+""+stmt2);
					parameterChklstDrvStmntMap.put("statement2", stmt1+""+stmt2);

				}else if(BankAuditConstant.COMPLIANCE_NO.equalsIgnoreCase(statement2.getComplianceCategory()) 
						&& !BankAuditConstant.NO.equalsIgnoreCase(statement2.getStandardStmntNonCompliancePrint())){
					
					String stmt1 = statement2.getStandardStmntNonCompliance()==null?"":(statement2.getStandardStmntNonCompliance()+"<br/>");
					String stmt2 = statement2.getFindingRemarks()==null?"":(statement2.getFindingRemarks());
					auditLettersJasperDto.setStatement2(stmt1+""+stmt2);
					parameterChklstDrvStmntMap.put("statement2", stmt1+""+stmt2);
					
				}
			} 
		}else if(letterCode.equalsIgnoreCase(BankAuditConstant.LETTER_CODE_RN)){
						
			/*AuditObservationLetterDto statementRN_6_1_3 = chklstDrvStmntMap.get("6.1.3");	
			AuditObservationLetterDto statementRN_6_1_4 = chklstDrvStmntMap.get("6.1.4");	
			AuditObservationLetterDto statementRN_6_1_5 = chklstDrvStmntMap.get("6.1.5");	
			AuditObservationLetterDto statementRN_6_1_6 = chklstDrvStmntMap.get("6.1.6");
			AuditObservationLetterDto statementRN_6_4_2 = chklstDrvStmntMap.get("6.4.2");
			AuditObservationLetterDto statementRN_6_5_2 = chklstDrvStmntMap.get("6.5.2");
			AuditObservationLetterDto statementRN_6_6_2 = chklstDrvStmntMap.get("6.6.2");
			
			if(statementRN_6_1_3!=null){ 
				parameterChklstDrvStmntMap.put("6.1.3",statementRN_6_1_3.getComplianceCategory());
			}
			if(statementRN_6_1_4!=null){ 
				parameterChklstDrvStmntMap.put("6.1.4",statementRN_6_1_4.getComplianceCategory());
			}
			if(statementRN_6_1_5!=null){  
				parameterChklstDrvStmntMap.put("6.1.5",statementRN_6_1_5.getComplianceCategory());
			}
			if(statementRN_6_1_6!=null){ 
				parameterChklstDrvStmntMap.put("6.1.6",statementRN_6_1_6.getComplianceCategory());
			}			
			if(statementRN_6_4_2!=null){ 
				parameterChklstDrvStmntMap.put("6.4.2",statementRN_6_4_2.getComplianceCategory());
			}
			if(statementRN_6_5_2!=null){ 
				parameterChklstDrvStmntMap.put("6.5.2",statementRN_6_5_2.getComplianceCategory());
			}
			if(statementRN_6_6_2!=null){ 
				parameterChklstDrvStmntMap.put("6.6.2",statementRN_6_6_2.getComplianceCategory());
			}*/
			
			AuditObservationLetterDto statementRN_12_1_X = chklstDrvStmntMap.get("12.1.X");
			if(statementRN_12_1_X!=null){
				parameterChklstDrvStmntMap.put("statementDrv_12.1.X", statementRN_12_1_X.getDerivedStatement());
			}
			
			//update supervisoryRating score from audit_schedule table
			parameterMap.put("3BOMS650", auditRating.getSupervisoryRiskPrcntg());  //Rating 
			parameterMap.put("3BOMS651", auditRating.getSupervisoryRating()); //category		 
		}

		auditLettersJasperDto.setStatementsRemarksList(statementsRemarksListUpdated);
		auditLettersJasperDto.setParameterMap(parameterMap);
		auditLettersJasperDto.setDliDpiParamMap(interfaceParameterService.getDliDpiDetailsByAuditId(legalEntityCode, auditId, null));
		auditLettersJasperDto.setParameterChklstDrvStmntMap(parameterChklstDrvStmntMap);
		return auditLettersJasperDto;
	}
	
	private String processBiLingualFwdLetters(Integer legalEntityCode, String auditTypeCode, String auditId, String letterCode, String status, Map<String, Object> params) throws JRException{
		AuditLettersDto auditLettersDto = lettersDao.getBiLingualLetterByAuditIdAndLetterCode(legalEntityCode, auditTypeCode, auditId, letterCode, status);
		List<AuditLetterBiLingualDto> auditLetterBiLingualDtoList = new ArrayList<>();
		if(!BankAuditConstant.STATUS_AUTH.equalsIgnoreCase(status)){
			List<AuditLetterBiLingualWrk> auditLetterBiLingualWrkList = auditLettersDto.getAuditLetterBiLingualWrkList();
			for (AuditLetterBiLingualWrk auditLetterBiLingualWrk : auditLetterBiLingualWrkList) {
				AuditLetterBiLingualDto auditLetterBiLingualDto = new AuditLetterBiLingualDto();
				BeanUtils.copyProperties(auditLetterBiLingualWrk, auditLetterBiLingualDto); 
				auditLetterBiLingualDtoList.add(auditLetterBiLingualDto);
			}
		}else{
			List<AuditLetterBiLingual> auditLetterBiLingualList = auditLettersDto.getAuditLetterBiLingualList();
			for (AuditLetterBiLingual auditLetterBiLingual : auditLetterBiLingualList) {
				AuditLetterBiLingualDto auditLetterBiLingualDto = new AuditLetterBiLingualDto();
				BeanUtils.copyProperties(auditLetterBiLingual, auditLetterBiLingualDto); 
				auditLetterBiLingualDtoList.add(auditLetterBiLingualDto);
			}
		}
		 		
		String letterPath = "/letters/";
		String subReportDir = "/letters/";
		String jasperReportName = "ForwardingLetter_Bi_Lingual.jrxml";  
		String letterName = letterCode+"_LetterBiLingual";
		
		InputStream stream = this.getClass().getResourceAsStream(letterPath + jasperReportName);			 
		JasperReport jasperReport   = JasperCompileManager.compileReport(stream);
		params.put("SUB_REPORT_DIR", subReportDir); 			
		 		 
		JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(auditLetterBiLingualDtoList);
		JasperPrint print = JasperFillManager.fillReport(jasperReport, params, dataSource);			 
		
		String uploadFileName = legalEntityCode+"_"+auditId+"_"+letterCode+"_TMP_"+new SimpleDateFormat("ddMMyyyy").format(new Date())+"_"+letterName+".pdf";			
		String generatedLettersPath = BankAuditConfig.getInstance().getConfigValue(BankAuditConstant.DIR_DOC_UPLOAD_JASPER_TMP)+ "/" +uploadFileName;
		JasperExportManager.exportReportToPdfFile(print, generatedLettersPath); 
		if(BankAuditConstant.STATUS_AUTH.equalsIgnoreCase(status)){					
			//merge letters 
			generatedLettersPath = mergeLettesAndUploadedPdf(legalEntityCode, auditId, auditTypeCode, letterCode, generatedLettersPath, letterName, true);				
			//save letters									 
			if(generatedLettersPath!=null){  
				String uploadStatus = saveAuditLetters(auditLettersDto.getAdtLtr(), legalEntityCode, auditId, letterCode, generatedLettersPath, uploadFileName);			
				return uploadStatus;
			} 
		}else if(BankAuditConstant.STATUS_UNAUTH.equalsIgnoreCase(status)){			 
			//merge letters 
			generatedLettersPath = mergeLettesAndUploadedPdf(legalEntityCode, auditId, auditTypeCode, letterCode, generatedLettersPath, letterName, false);
			return generatedLettersPath;
		}	
		return BankAuditConstant.FAILED;
	}
	
	private String mergeLettesAndUploadedPdf(Integer legalEntityCode, String auditId, String auditTypeCode, String letterDocumentTypeCode, String generatedLettersPath, String letterName, Boolean isFinal){
		
		String uploadFileName = legalEntityCode+"_"+auditId+"_"+auditTypeCode+"_"+new SimpleDateFormat("ddMMyyyy").format(new Date())+"_"+letterName+".pdf";			
		String uploadPath = "";
		if(isFinal && !BankAuditConstant.LETTER_CODE_RN.equalsIgnoreCase(letterDocumentTypeCode) ){
			 uploadPath = BankAuditConfig.getInstance().getConfigValue(BankAuditConstant.DIR_DOC_UPLOAD_LETTERS)+ "/" +uploadFileName;			  
		}else{
			 uploadPath = BankAuditConfig.getInstance().getConfigValue(BankAuditConstant.DIR_DOC_UPLOAD_JASPER_TMP)+ "/" +uploadFileName;
		}
		PDFMergerUtility pdfMerger = new PDFMergerUtility();		
		pdfMerger.setDestinationFileName(uploadPath);		
		List<String>  listPdfs = lettersDao.getLettersPdfFiles(legalEntityCode, auditId, auditTypeCode, letterDocumentTypeCode);		
		try{ 
			pdfMerger.addSource(generatedLettersPath);
			if(listPdfs!=null && !listPdfs.isEmpty()){
				for (String pdf : listPdfs) {			
					File pdfFile = new File(pdf);				
					pdfMerger.addSource(pdfFile);			 	
				}				
			} 
			pdfMerger.mergeDocuments(null); 
			
			//Adding page number 
			if(BankAuditConstant.LETTER_CODE_RN.equalsIgnoreCase(letterDocumentTypeCode)){
				String FilePathFinal=null;
				if(isFinal){
					FilePathFinal = BankAuditConfig.getInstance().getConfigValue(BankAuditConstant.DIR_DOC_UPLOAD_LETTERS)+ "/RN_" +uploadFileName;			  
				}else{
					FilePathFinal = BankAuditConfig.getInstance().getConfigValue(BankAuditConstant.DIR_DOC_UPLOAD_JASPER_TMP)+ "/RN_" +uploadFileName;
				}
				
				PdfReader reader = new PdfReader(uploadPath);
				int pageCount = (reader.getNumberOfPages());
				PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(FilePathFinal));
				int pageNumber = 0;
				PdfContentByte over ;
				BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
				while (pageNumber < pageCount) {
					pageNumber++;					 
					over = stamp.getOverContent(pageNumber);
					over.beginText();
					over.setFontAndSize(bf, 10);						 
					over.showTextAligned(PdfContentByte.ALIGN_LEFT, String.format("page %s of %s", pageNumber, pageCount), 72, 55, 0);
					over.endText(); 					 
				}
				stamp.close();					
				try{ 	
					 File IR_fileToDelete = new File(uploadPath)  ;
					 IR_fileToDelete.delete();
				}catch (Exception e) { return null; } 
				return FilePathFinal;
			}
			return uploadPath;
		}catch (IOException e) { 
			return null;
		} catch (Exception e) { 
			return null;
		} 		
	} 
	
	@Override
	public DataTableResponse getLetterForReviewer(int legalEntityCode, String userId, String search,Integer orderColumn,
			String orderDirection, Integer page, Integer size, String role, String userUnitType, LocalDate financialYear, String auditTypeCode){	
		//return lettersDao.getLetterForReviewer(legalEntityCode, userId, search, orderColumn, orderDirection, page, size, role, userUnitType);
		List<LocalDate>  financialYearStrtEndList=null;
		if(financialYear!=null) financialYearStrtEndList= BankAuditUtil.getFinancialStartEndDatesNxtFrom(financialYear);
		List<String> unitList =  maintEntityService.getSubBranchesGyUserIdOrUnitId(legalEntityCode,"user",userId); 
		return lettersDao.getAllLetterForReviewer(legalEntityCode, userId, search, orderColumn, orderDirection, page, size, role, userUnitType, unitList,
				financialYear, auditTypeCode, financialYearStrtEndList);
	}
	
	@Override
	public Integer isRatingCompleted(Integer legalEntityCode, String auditTypeCode, String auditId)  {
		logger.info("Inside isRatingCompleted .. "+legalEntityCode +" :: "+auditTypeCode+" ::"+ auditId);
		try { 		 
				return lettersDao.isRatingCompleted(legalEntityCode, auditTypeCode, auditId);			 
		}catch(Exception e) {
			e.printStackTrace(System.out);
			return -1;
		}
	}
	
	@Override
	public Integer isLetterAuthorised(Integer legalEntityCode, String auditTypeCode, String auditId, String letterCode)  {
		logger.info("Inside isLetterAuthorised .. "+legalEntityCode +" :: "+auditTypeCode+" ::"+ auditId+" :: "+ letterCode);
		try { 		 
				return lettersDao.isLetterAuthorised(legalEntityCode, auditTypeCode, auditId, letterCode);			 
		}catch(Exception e) {
			e.printStackTrace(System.out);
			return -1;
		}
	} 
	
	@Override
	public DataTableResponse getLetterForReviewerGradingCompliance(int legalEntityCode, String userId, String search,Integer orderColumn,
			String orderDirection, Integer page, Integer size, String role, String userUnitType, LocalDate financialYear, String auditTypeCode){
		List<LocalDate>  financialYearStrtEndList=null;
		if(financialYear!=null) financialYearStrtEndList= BankAuditUtil.getFinancialStartEndDatesNxtFrom(financialYear);
		return lettersDao.getLetterForReviewerGradingCompliance(legalEntityCode, userId, search, orderColumn, orderDirection, page, size, role, userUnitType,
				financialYear, auditTypeCode, financialYearStrtEndList);
	}
	
	private void saveLetterStatusLogs(AuditLetterUserInputsWrk adtLtrWrk, String status){
		
		logger.info("Inside saveLetterStatusLogs .. "+ adtLtrWrk.getAuditId()+" :: "+ status );
		Map<String, Object> properties = new HashMap<>();
		properties.put("legalEntityCode", adtLtrWrk.getLegalEntityCode());
		properties.put("auditId", adtLtrWrk.getAuditId());
		properties.put("auditTypeCode", adtLtrWrk.getAuditTypeCode());			
		AuditSchedule auditSchedule = (AuditSchedule) lettersDao.getUniqueEntityByMatchingProperties(AuditSchedule.class, properties);	
		
		if(BankAuditConstant.STATUS_AUTH.equalsIgnoreCase(status) ||
				(BankAuditConstant.STATUS_REJ.equalsIgnoreCase(status) && adtLtrWrk.getAssigneeId().equalsIgnoreCase(adtLtrWrk.getActionMakerId()))){
			adtLtrWrk.setAssigneeId(null);
		}
		
		auditSchedule.setAssigneeId(adtLtrWrk.getAssigneeId());
		auditSchedule.setActionMakerId(adtLtrWrk.getActionMakerId());
		auditSchedule.setActionMakerRole(adtLtrWrk.getActionMakerRole()); 			
				
		AuditScheduleStagesStatusHst auditScheduleStagesStatusHst = new AuditScheduleStagesStatusHst();
		Map<String, Object> auditSchStagesStatusHstProperties = new HashMap<String, Object>();
		auditSchStagesStatusHstProperties.put("legalEntityCode", auditSchedule.getLegalEntityCode());
		auditSchStagesStatusHstProperties.put("auditTypeCode", auditSchedule.getAuditTypeCode());
		auditSchStagesStatusHstProperties.put("auditId", auditSchedule.getAuditId());
		auditSchStagesStatusHstProperties.put("actionType", BankAuditConstant.ACTION_TYPE_LETTER);
		auditSchStagesStatusHstProperties.put("code", adtLtrWrk.getLetterCode());			
		auditSchStagesStatusHstProperties.put("stagesStatus", status);					
		auditSchStagesStatusHstProperties.put("makerId",  auditSchedule.getActionMakerId());	
		 		
		if(!BankAuditUtil.isEmptyString(adtLtrWrk.getAssigneeId())){
			auditScheduleStagesStatusHst.setAssigneeRole("G12");
			auditSchStagesStatusHstProperties.put("assigneeId", adtLtrWrk.getAssigneeId());
		}		
		
		/*AuditScheduleStagesStatusHst  auditScheduleStagesStatusHstChk = 
				(AuditScheduleStagesStatusHst) myAuditsDao.getUniqueEntityByMatchingProperties(AuditScheduleStagesStatusHst.class, auditSchStagesStatusHstProperties);*/
		AuditScheduleStagesStatusHst  auditScheduleStagesStatusHstChk = auditScheduleStagesStatusHstService.getLatestRecordByMatchingProperties(auditSchStagesStatusHstProperties);
		if(auditScheduleStagesStatusHstChk != null){ 
			auditScheduleStagesStatusHst.setId(auditScheduleStagesStatusHstChk.getId());
		}  									 
		 
		if (BankAuditConstant.STATUS_REJ.equalsIgnoreCase(status)) {
			auditScheduleStagesStatusHst.setAssigneeRole("G8");  // In case of Reject, the Assignee is PIO
		}
		
		auditScheduleStagesStatusHst.setStagesStatus(status);
		auditScheduleStagesStatusHst.setCode(adtLtrWrk.getLetterCode());
		auditScheduleStagesStatusHst.setActionType(BankAuditConstant.ACTION_TYPE_LETTER);		 
		auditScheduleStagesStatusHstService.saveAuditStagesStatus(auditSchedule, auditScheduleStagesStatusHst); 
	}
	 
}
