package com.bankaudit.rest.process.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bankaudit.dao.GeneralParameterDao;
import com.bankaudit.dto.process.EmailTemplateDto;
import com.bankaudit.model.GeneralParameter;
import com.bankaudit.model.MaintAuditTypeDesc;
import com.bankaudit.model.User;
import com.bankaudit.rest.process.dao.EmailDao;
import com.bankaudit.rest.process.dao.MyAuditsDao;
import com.bankaudit.service.MaintAuditTypeDescService;
import com.bankaudit.service.UserService;
import com.bankaudit.spring.config.EmailConfig;
import com.bankaudit.util.BankAuditUtil;
import com.bankaudit.util.EmailTemplates;

@Service("emailService")
@Transactional("transactionManager")
public class EmailServiceImpl implements EmailService {
	
	@Autowired
	private EmailConfig emailConfig;
	
	@Autowired
    private Environment environment;
	
	@Autowired
	private EmailDao emailDao;
	
	@Autowired
	private MyAuditsDao auditsDao;
	
	@Autowired
    private GeneralParameterDao generalParameterDao;
	
	@Autowired
    private AuditObservationService auditObservationService;
	
	@Autowired
    private UserService userService;
	
	@Autowired
	MaintAuditTypeDescService maintAuditTypeDescService;
	
	static final Logger logger = Logger.getLogger(EmailServiceImpl.class);
	
	public void sendEmail(List<String> to, List<String> cc, List<String> bcc, String fromAddress,String subject, String template) throws InvalidToListException{
		logger.info("Inside sendEmail .. to.."+ to+" cc.."+cc+" fromAddress.."+fromAddress +" subject.. "+subject);
		
		try {
			//cc.add("ravikumar.t@finakon.in");cc.add("ramya.s@finakon.in");cc.add("sudip.rai@finakon.in");// Code to Comment
			bcc.add("debasish.swain@caprusit.com");
			
			if (!(to.size() > 0)) {
				throw new InvalidToListException("To list should not be empty");
			}
			MimeMessage message = new MimeMessage(getsession());
			message.setFrom(new InternetAddress(fromAddress));
			
			for (String x : to) message.addRecipient(Message.RecipientType.TO, new InternetAddress(x)); // to list
			if(cc !=null) for (String x : cc) message.addRecipient(Message.RecipientType.CC, new InternetAddress(x));	// cc list		
			if(bcc!=null)for (String x : bcc) message.addRecipient(Message.RecipientType.BCC, new InternetAddress(x)); // bcc list
			
			message.setSubject(subject);
	        message.setContent(template.toString(), "text/html");
		        //message.setContent("<h1>This is actual message embedded in HTML tags</h1>", "text/html");
			Transport.send(message);
			logger.info("===== Email send =====");
		} catch (MessagingException mex) {
			mex.printStackTrace();
		}
	}
	
	public Session getsession() {
		logger.info(" Host:::::::::::::"+environment.getRequiredProperty("email.host"));
		logger.info(" Auth:::::::::::::"+environment.getRequiredProperty("email.auth"));
		logger.info(" starttls.enable::"+environment.getRequiredProperty("email.starttls.enable"));
		logger.info(" Port:::::::::::::"+environment.getRequiredProperty("email.port"));
		logger.info(" User:::::::::::::"+environment.getRequiredProperty("email.user"));
		
		String host = environment.getRequiredProperty("email.host");
		Properties properties = System.getProperties();
		properties.put("mail.smtp.auth", environment.getRequiredProperty("email.auth"));
		properties.put("mail.smtp.starttls.enable", environment.getRequiredProperty("email.starttls.enable"));
		properties.put("mail.smtp.host", host);
		properties.put("mail.smtp.port", environment.getRequiredProperty("email.port"));
		Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				 return new PasswordAuthentication(environment.getRequiredProperty("email.user"), environment.getRequiredProperty("email.pass"));
				// return new PasswordAuthentication("anilkumar.chintala@caprusit.com", "Abhi@2022");
			}
		});
		return session;
	}
	
	/***********************************  Email template for BaaS DOS, Start here *****************************************/
	@Override
	public String sendInspectionInitiate(Integer legalEntityCode, String auditId) {
		String template=null;
		try {
			logger.info("Inside SendInspectionInitiate .."+legalEntityCode +" :: "+auditId);
			EmailTemplateDto emailDto= emailDao.getAuditEmailDetailsbyAuditId(legalEntityCode, auditId);
			List<String> to = new ArrayList<String>(); to.add(emailDto.getParentEmailId()); //  to.add("debasish.swain@caprusit.com");
			List<String> cc = new ArrayList<String>(); //cc.add(emailDto.getParentEmailId()); // cc.add(complianceEvent.getResponsibleEmail());
			List<String> bcc = new ArrayList<String>();
			//String subject=environment.getRequiredProperty("email.subject_on_compliance");
			String subject=EmailTemplates.getSubjectTemplate(emailDto, "AI");
			sendEmail( to,  cc,  bcc,  environment.getRequiredProperty("email.from"),subject, EmailTemplates.getInspectionInitiateTemplate(emailDto ,"TMPLT1"));
			//sendEmail( to,  cc,  bcc,  "anilkumar.chintala@caprusit.com",subject, getEmailOnComplianceTemplate(complianceEvent));
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
		return template;
	}
	
	@Override
	public String sendInspectionExit(Integer legalEntityCode, String auditId) {
		String template=null;
		try {
			logger.info("Inside sendInspectionExit .."+legalEntityCode +" :: "+auditId);
			EmailTemplateDto emailDto= emailDao.getAuditEmailDetailsbyAuditId(legalEntityCode, auditId);
			List<String> to = new ArrayList<String>(); to.add(emailDto.getParentEmailId()); //  to.add("debasish.swain@caprusit.com");
			List<String> cc = new ArrayList<String>(); //cc.add(emailDto.getParentEmailId()); // cc.add(complianceEvent.getResponsibleEmail());
			List<String> bcc = new ArrayList<String>();
			String subject=EmailTemplates.getSubjectTemplate(emailDto, "AE");
			sendEmail( to,  cc,  bcc,  environment.getRequiredProperty("email.from"),subject, EmailTemplates.getInspectionExitTemplate(emailDto ,"TMPLT2"));
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
		return template;
	}
	
	@Override
	public String sendReadyForReview(Integer legalEntityCode, String auditId) {
		String template=null;
		try {
			logger.info("Inside sendReadyForReview .."+legalEntityCode +" :: "+auditId);
			EmailTemplateDto emailDto= emailDao.getAuditEmailDetailsbyAuditId(legalEntityCode, auditId);
			List<String> to = new ArrayList<String>(); to.add(emailDto.getParentEmailId()); // to.add("debasish.swain@caprusit.com");
			List<String> cc = new ArrayList<String>(); //cc.add(emailDto.getParentEmailId()); // cc.add(complianceEvent.getResponsibleEmail());
			List<String> bcc = new ArrayList<String>();
			String subject=EmailTemplates.getSubjectTemplate(emailDto, "RAR");
			sendEmail( to,  cc,  bcc,  environment.getRequiredProperty("email.from"),subject, EmailTemplates.getReadyForReviewTemplate(emailDto ,"TMPLT3"));
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
		return template;
	}
	
	
	@Override
	public String sendInspectionDispatch(Integer legalEntityCode, String auditId) {
		String template=null;
		try {
			logger.info("Inside sendInspectionDispatch .."+legalEntityCode +" :: "+auditId);
			EmailTemplateDto emailDto= emailDao.getAuditEmailDetailsbyAuditId(legalEntityCode, auditId);
			List<String> to = new ArrayList<String>(); to.add(emailDto.getUnitEmailId()); // to.add("debasish.swain@caprusit.com");
			List<String> cc = new ArrayList<String>(); cc.add(emailDto.getParentEmailId());cc.add(emailDto.getHOEmailId()); // cc.add(complianceEvent.getResponsibleEmail());
			List<String> bcc = new ArrayList<String>();
			String subject=EmailTemplates.getSubjectTemplate(emailDto, "AS");
			sendEmail( to,  cc,  bcc,  environment.getRequiredProperty("email.from"),subject, EmailTemplates.getInspectionDispatchTemplate(emailDto ,"TMPLT4"));
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
		return template;
	}
	
	@Override
	public String sendComplianceSubmission(Integer legalEntityCode, String auditId) {
		String template=null;
		try {
			logger.info("Inside sendComplianceSubmission .."+legalEntityCode +" :: "+auditId);
			EmailTemplateDto emailDto= emailDao.getAuditEmailDetailsbyAuditId(legalEntityCode, auditId);
			User usr=userService.getUserByLegalEntityCodeAndUserId(legalEntityCode,emailDto.getBankUserId());
			emailDto.setBankUserName(usr.getFirstName()+" "+(usr.getLastName()!=null?usr.getLastName():""));
			emailDto.setBankUserDesignation(usr.getDesignation());
			List<String> to = new ArrayList<String>(); to.add(emailDto.getParentEmailId()); // to.add("debasish.swain@caprusit.com");
			List<String> cc = new ArrayList<String>(); cc.add(emailDto.getUnitEmailId()); // UnComment cc.add(complianceEvent.getResponsibleEmail());
			List<String> bcc = new ArrayList<String>();
			String subject=EmailTemplates.getSubjectTemplate(emailDto, "AR");
			sendEmail( to,  cc,  bcc,  environment.getRequiredProperty("email.from"),subject, EmailTemplates.getComplianceSubmissionTemplate(emailDto ,"TMPLT5"));
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
		return template;
	}
	
	@Override
	public String sendFurtherCompliance(Integer legalEntityCode, String auditId) { // Compliance Reject case
		String template=null;
		try {
			logger.info("Inside sendFurtherCompliance .."+legalEntityCode +" :: "+auditId);
			int furtherComp= auditObservationService.getCountRespondRejectedRecords(legalEntityCode, auditId);
			if(furtherComp >0) { // Email will be sent if there is at least 1 further compliance/Respond rejected record.
				EmailTemplateDto emailDto= emailDao.getAuditEmailDetailsbyAuditId(legalEntityCode, auditId);
				User usr=userService.getUserByLegalEntityCodeAndUserId(legalEntityCode,emailDto.getReveiwerId());
				emailDto.setCompFurtherRecords(furtherComp);
				emailDto.setReveiwerName(usr.getFirstName()+" "+usr.getLastName()!=null?usr.getLastName():"");
				emailDto.setReveiwerDesignation(usr.getDesignation());
				List<String> to = new ArrayList<String>(); to.add(emailDto.getUnitEmailId()); // to.add("debasish.swain@caprusit.com");
				List<String> cc = new ArrayList<String>(); cc.add(emailDto.getParentEmailId()); // cc.add(complianceEvent.getResponsibleEmail());
				List<String> bcc = new ArrayList<String>();
				String subject=EmailTemplates.getSubjectTemplate(emailDto, "AW");
				sendEmail( to,  cc,  bcc,  environment.getRequiredProperty("email.from"),subject, EmailTemplates.getFurtherComplianceTemplate(emailDto ,"TMPLT6"));
			}
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
		return template;
	}
	
	
	
	/******************** New Triggers, for Inspection Report review process ************************/
	/************************** 
	 * RRR -> When clicked by PIO, for Review
	 * RAR -> When Allocator allocates to Reviewer
	 * RC  -> hen Reviewer completes Review
	 * FS  -> When PIO re-submit for review
	 * RA  -> When Reviewer accepted Review
	 * RS  -> When Reviewer finalized inspection	 
	 */	
	@Override
	public String sendEmailDuringInpsectionReview(Integer legalEntityCode, String auditId, String inspRptStatus) {
		String template=null;
		try {
			logger.info("Inside sendEmailDuringInpsectionReview .."+legalEntityCode +" :: "+auditId+" :: "+inspRptStatus);
			EmailTemplateDto emailDto= emailDao.getAuditReviewEmailDetailsbyAuditId(legalEntityCode, auditId);
			List<String> to = new ArrayList<String>(); // to.add(emailDto.getParentEmailId()); // to.add("debasish.swain@caprusit.com");
			List<String> cc = new ArrayList<String>(); //cc.add(emailDto.getParentEmailId()); // cc.add(complianceEvent.getResponsibleEmail());
			List<String> bcc = new ArrayList<String>();  bcc.add("debasish.swain@caprusit.com");
			
			if("RRR".equalsIgnoreCase(inspRptStatus)) { 
				logger.info("RRR => Alcs Mail ::"+ emailDto.getAllocatorsEmail() +" Lead:: "+ emailDto.getLeadEmail()+" Mbr:: "+emailDto.getMemberEmails());
				if(emailDto.getAllocatorsEmail()!=null) to.addAll(BankAuditUtil.convertStringToList(emailDto.getAllocatorsEmail()));
				cc.add(emailDto.getLeadEmail());
				if(emailDto.getMemberEmails()!=null) cc.addAll(BankAuditUtil.convertStringToList(emailDto.getMemberEmails()));
			}else if("RAR".equalsIgnoreCase(inspRptStatus)) { // When Allocator allocates to Reviewer
				logger.info("RAR => Rvwr Mail ::"+ emailDto.getReportReveiwerEmail() +" Lead:: "+ emailDto.getLeadEmail()+" Mbr:: "+emailDto.getMemberEmails());
				if(emailDto.getReportReveiwerEmail()!=null)to.add(emailDto.getReportReveiwerEmail());
				cc.add(emailDto.getLeadEmail());
				if(emailDto.getMemberEmails()!=null) cc.addAll(BankAuditUtil.convertStringToList(emailDto.getMemberEmails()));
			}else if("RC".equalsIgnoreCase( inspRptStatus)) {  // When Reviewer completes Review
				logger.info("RC => Rvwr Mail ::"+ emailDto.getReportReveiwerEmail() +" Lead:: "+ emailDto.getLeadEmail()+" Mbr:: "+emailDto.getMemberEmails());
				to.add(emailDto.getLeadEmail());
				if(emailDto.getMemberEmails()!=null) to.addAll(BankAuditUtil.convertStringToList(emailDto.getMemberEmails()));
				if(emailDto.getReportReveiwerEmail()!=null)cc.add(emailDto.getReportReveiwerEmail());
			}else if("FS".equalsIgnoreCase( inspRptStatus)) {  // When PIO re-submit for review
				logger.info("FS => Rvwr Mail ::"+ emailDto.getReportReveiwerEmail() +" Lead:: "+ emailDto.getLeadEmail()+" Mbr:: "+emailDto.getMemberEmails());
				if(emailDto.getReportReveiwerEmail()!=null)to.add(emailDto.getReportReveiwerEmail());
				cc.add(emailDto.getLeadEmail());
				if(emailDto.getMemberEmails()!=null) cc.addAll(BankAuditUtil.convertStringToList(emailDto.getMemberEmails()));
			}else if("RR".equalsIgnoreCase( inspRptStatus)) {  // When Reviewer provide Rejected/Feedback 
				logger.info("RR => Rvwr Mail ::"+ emailDto.getReportReveiwerEmail() +" Lead:: "+ emailDto.getLeadEmail()+" Mbr:: "+emailDto.getMemberEmails());
				to.add(emailDto.getLeadEmail());
				if(emailDto.getMemberEmails()!=null) to.addAll(BankAuditUtil.convertStringToList(emailDto.getMemberEmails()));
				if(emailDto.getReportReveiwerEmail()!=null)cc.add(emailDto.getReportReveiwerEmail());
			}else if("RA".equalsIgnoreCase( inspRptStatus)) {  // When Reviewer accepted Review
				logger.info("RA => Alc Mail ::"+emailDto.getAllocatorsEmail() +" Rvwr Mail ::"+ emailDto.getReportReveiwerEmail() +" Lead:: "+ emailDto.getLeadEmail()+" Mbr:: "+emailDto.getMemberEmails());
				if(emailDto.getAllocatorEmail()!=null) to.add(emailDto.getAllocatorEmail());
				if(emailDto.getReportReveiwerEmail()!=null) cc.add(emailDto.getReportReveiwerEmail());
				cc.add(emailDto.getLeadEmail());
				if(emailDto.getMemberEmails()!=null) cc.addAll(BankAuditUtil.convertStringToList(emailDto.getMemberEmails()));
			}else if("RS".equalsIgnoreCase( inspRptStatus)) {  // When Reviewer finalized inspection
				logger.info("RS => Rvwr Mail ::"+ emailDto.getReportReveiwerEmail() +" Lead:: "+ emailDto.getLeadEmail()+" Mbr:: "+emailDto.getMemberEmails());
				to.add(emailDto.getLeadEmail());
				if(emailDto.getMemberEmails()!=null) to.addAll(BankAuditUtil.convertStringToList(emailDto.getMemberEmails()));
				if(emailDto.getReportReveiwerEmail()!=null)cc.add(emailDto.getReportReveiwerEmail());
			}
			logger.info("to mailid :: "+to);
			logger.info("cc mailid :: "+cc);			
			
			String subject=EmailTemplates.getSubjectAuditReviewTemplate(emailDto, inspRptStatus);
			sendEmail( to,  cc,  bcc,  environment.getRequiredProperty("email.from"),subject, EmailTemplates.getReviewTemplate(emailDto ,inspRptStatus));
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
		return template;
	}
	
	@Override
	public String sendScurityAssigned(Integer legalEntityCode, String auditId) {
		String template=null;
		try {
			logger.info("Inside sendScurityAssigned .."+legalEntityCode +" :: "+auditId);
			EmailTemplateDto emailDto= emailDao.getAuditReviewEmailDetailsbyAuditId(legalEntityCode, auditId);
			List<String> to = new ArrayList<String>();  // to.add("debasish.swain@caprusit.com");
			List<String> cc = new ArrayList<String>();  //cc.add(emailDto.getParentEmailId()); // cc.add(complianceEvent.getResponsibleEmail());
			List<String> bcc = new ArrayList<String>();  bcc.add("debasish.swain@caprusit.com");
			
			if(emailDto.getReveiwerEmail()!=null) to.add(emailDto.getReveiwerEmail());
			if(emailDto.getLeadReveiwerEmail()!=null) cc.add(emailDto.getLeadReveiwerEmail());
			
			String subject=EmailTemplates.getSubjectAuditReviewTemplate(emailDto, "WI");
			sendEmail( to,  cc,  bcc,  environment.getRequiredProperty("email.from"),subject, EmailTemplates.getScrutinyAssignTemplate(emailDto ,"WI"));
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
		return template;
	}
	/******************** End Here ****************************/
	
	
	
	/*************************************** Email template for BaaS DOS, End here  *******************************************/
	
	/*********************** Batch Email Trigger BaaSDOS  	*****************************************/
	/*@Override
	public String sendEmailForInspectionNotification(Integer legalEntityCode) {
		try {
			logger.info("Inside sendEmailForInspectionNotification "+legalEntityCode);
			List<MaintAuditTypeDesc> auditTypeLst= maintAuditTypeDescService.getMaintAuditTypeDescByLegalEntityCode(legalEntityCode);
			for(MaintAuditTypeDesc auditType: auditTypeLst) {
				logger.info("for AuditType .."+auditType.getAuditTypeDesc());
				String status= sendEmailForInspectionNotificationAuditTypeWise(legalEntityCode, auditType.getAuditTypeCode());
			}
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
		return "Success";
	}*/
	
	@Override
	public String sendEmailForInspectionNotification(Integer legalEntityCode) { 
		String template=null;
		try {
			logger.info("Inside sendEmailForInspectionNotificationAuditTypeWise .."+legalEntityCode );
			
			List<EmailTemplateDto> emailDtos= emailDao.getAuditEmailDetailsForNotification(legalEntityCode, "1"); 
			for(EmailTemplateDto emailDto: emailDtos) {
				String auditSlNo=auditsDao.getAuditSerialNoBfrInitiate(legalEntityCode, emailDto.getAuditId(), "", emailDto.getUnitCode(), emailDto.getAuditTypeCode());
				emailDto.setAuditSerialNo(auditSlNo);
				
				List<String> to = new ArrayList<String>(); to.add(emailDto.getUnitEmailId()); // to.add("debasish.swain@caprusit.com");
				List<String> cc = new ArrayList<String>(); cc.add(emailDto.getParentEmailId()); // cc.add(complianceEvent.getResponsibleEmail());
				List<String> bcc = new ArrayList<String>();
				String subject=EmailTemplates.getSubjectTemplate(emailDto, "1ST_NOTIFICATION");
				sendEmail( to,  cc,  bcc,  environment.getRequiredProperty("email.from"),subject, EmailTemplates.get1stNotificationTemplate(emailDto ,"TMPLT7"));
			}	
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
		return template;
	}
	

	/*@Override
	public String sendEmailForInspection2ndNotification(Integer legalEntityCode) {
		try {
			logger.info("Inside sendEmailForInspectionNotification "+legalEntityCode);
			List<MaintAuditTypeDesc> auditTypeLst= maintAuditTypeDescService.getMaintAuditTypeDescByLegalEntityCode(legalEntityCode);
			for(MaintAuditTypeDesc auditType: auditTypeLst) {
				logger.info("for AuditType .."+auditType.getAuditTypeDesc());
				String status= sendEmailForInspection2ndNotificationAuditTypeWise(legalEntityCode, auditType.getAuditTypeCode());
			}
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
		return "Success";
	}*/
	
	public String sendEmailForInspection2ndNotification(Integer legalEntityCode) { 
		String template=null;
		try {
			logger.info("Inside sendEmailForInspection2ndNotification .."+legalEntityCode );
			
			List<EmailTemplateDto> emailDtos= emailDao.getAuditEmailDetailsForNotification(legalEntityCode, "2"); 
			for(EmailTemplateDto emailDto: emailDtos) {
				String auditSlNo=auditsDao.getAuditSerialNoBfrInitiate(legalEntityCode, emailDto.getAuditId(), "", emailDto.getUnitCode(), emailDto.getAuditTypeCode());
				emailDto.setAuditSerialNo(auditSlNo);
				
				List<String> to = new ArrayList<String>(); to.add(emailDto.getUnitEmailId()); // to.add("debasish.swain@caprusit.com");
				List<String> cc = new ArrayList<String>(); cc.add(emailDto.getParentEmailId()); // cc.add(complianceEvent.getResponsibleEmail());
				List<String> bcc = new ArrayList<String>();
				String subject=EmailTemplates.getSubjectTemplate(emailDto, "2ND_NOTIFICATION");
				sendEmail( to,  cc,  bcc,  environment.getRequiredProperty("email.from"),subject, EmailTemplates.get2ndNotificationTemplate(emailDto ,"TMPLT8"));
			}	
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
		return template;
	}
	/********************** Batch Email Trigger BaaSDOS, End here *******/
	
	/***** Baas DOS, Notifications Phase II *********/
	public String sendEmailBeforeDueExitAudit(Integer legalEntityCode, Map<String, String> thresholdMap) { 
		String template=null;
		try {
			logger.info("Inside sendEmailForInspection2ndNotification .."+legalEntityCode );
			
			List<EmailTemplateDto> emailDtos= emailDao.getAuditEmailDetailsForNotification(legalEntityCode, "BDAuditExit");  //, thresholdMap); 
			for(EmailTemplateDto emailDto: emailDtos) {
				String auditSlNo=auditsDao.getAuditSerialNoBfrInitiate(legalEntityCode, emailDto.getAuditId(), "", emailDto.getUnitCode(), emailDto.getAuditTypeCode());
				emailDto.setAuditSerialNo(auditSlNo);
				
				List<String> to = new ArrayList<String>(); to.add(emailDto.getUnitEmailId()); // to.add("debasish.swain@caprusit.com");
				List<String> cc = new ArrayList<String>(); cc.add(emailDto.getParentEmailId()); // cc.add(complianceEvent.getResponsibleEmail());
				List<String> bcc = new ArrayList<String>();
				String subject=EmailTemplates.getSubjectTemplate(emailDto, "2ND_NOTIFICATION");
				sendEmail( to,  cc,  bcc,  environment.getRequiredProperty("email.from"),subject, EmailTemplates.get2ndNotificationTemplate(emailDto ,"TMPLT8"));
			}	
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
		return template;
	}
	
	/***** Baas DOS, Notifications Phase II, End here *********/
	
	
	
	
	
	/*************************************** Email template for NABARD CRAR, Start here  *******************************************/
	public String sendEmailFirstNotification(Integer legalEntityCode) throws Exception{
		logger.info(" sendEmailFirstNotification => legalEntityCode .. "+ legalEntityCode);
		String sendStatus="Success";
		int daysBefore=10;
		/*List<GeneralParameter> getGeneralParameter= generalParameterDao.getGeneralParameter(legalEntityCode, null, null, "EMAIL_NOTIFICATION", "FIRST_NOTIFICATION", null, null);
		if(getGeneralParameter!=null && getGeneralParameter.size() >0 ) daysBefore= Integer.parseInt(getGeneralParameter.get(0).getValue());
		List<ComplianceEvent> complianceEvents= complianceEventService.getComplianceEventsForNotification(legalEntityCode, daysBefore);
		logger.info("complianceEvents .. "+ complianceEvents.size() +" class .. "+ complianceEvents.getClass());
		int i=0; String tmpAccEmail=null, tmpRspEmail=null; 
		List<ComplianceEvent> complianceEventsTmp= new ArrayList<>(); List<String> to = new ArrayList<String>(); List<String> bcc = new ArrayList<>(); 
		bcc.add("debasish.swain@caprusit.com");
		for(ComplianceEvent complianceEvent: complianceEvents) {
			String subject=environment.getRequiredProperty("email.subject_first_notification");
			if(i==0) {
				to.add(complianceEvent.getAccountableEmail()); to.add(complianceEvent.getResponsibleEmail());
				tmpAccEmail=complianceEvent.getAccountableEmail(); 
				tmpRspEmail=complianceEvent.getResponsibleEmail();
				complianceEventsTmp.add(complianceEvent);				
			}else if(tmpAccEmail.equalsIgnoreCase(complianceEvent.getAccountableEmail()) && tmpRspEmail.equalsIgnoreCase(complianceEvent.getResponsibleEmail())) {
				complianceEventsTmp.add(complianceEvent);
			}else {
				sendEmail( to,  null,  bcc,  environment.getRequiredProperty("email.from"),subject, getEmailDueComplianceTemplate(complianceEventsTmp, "TMPLT1"));
				complianceEventsTmp= new ArrayList<>(); to = new ArrayList<String>(); 
				to.add(complianceEvent.getAccountableEmail()); to.add(complianceEvent.getResponsibleEmail());
				tmpAccEmail=complianceEvent.getAccountableEmail(); 
				tmpRspEmail=complianceEvent.getResponsibleEmail();
				complianceEventsTmp.add(complianceEvent);
			}i++;
			if(i== complianceEvents.size()) {
				sendEmail( to,  null,  bcc,  environment.getRequiredProperty("email.from"),subject, getEmailDueComplianceTemplate(complianceEventsTmp, "TMPLT1"));
			}
						
		}*/
		return sendStatus;
	}
	
	public String sendEmailBeforeDueNotification(Integer legalEntityCode) throws Exception{
		logger.info(" sendEmailBeforeDueNotification => legalEntityCode .. "+ legalEntityCode);
		String sendStatus="Success";
		int daysBefore=2;
		/*List<GeneralParameter> getGeneralParameter= generalParameterDao.getGeneralParameter(legalEntityCode, null, null, "EMAIL_NOTIFICATION", "BEFORE_DUE_NOTIFICATION", null, null);
		if(getGeneralParameter!=null && getGeneralParameter.size() >0 ) daysBefore= Integer.parseInt(getGeneralParameter.get(0).getValue());
		List<ComplianceEvent> complianceEvents= complianceEventService.getComplianceEventsForNotification(legalEntityCode, daysBefore);
		logger.info(" complianceEvents .. "+ complianceEvents);
		int i=0; String tmpAccEmail=null, tmpRspEmail=null; 
		List<ComplianceEvent> complianceEventsTmp= new ArrayList<>(); List<String> to = new ArrayList<String>(); List<String> bcc = new ArrayList<>(); 
		bcc.add("debasish.swain@caprusit.com");
		String subject=environment.getRequiredProperty("email.subject_bfr_due_notification");
		for(ComplianceEvent complianceEvent: complianceEvents) {
			if(i==0) {
				to.add(complianceEvent.getAccountableEmail()); to.add(complianceEvent.getResponsibleEmail());
				tmpAccEmail=complianceEvent.getAccountableEmail(); 
				tmpRspEmail=complianceEvent.getResponsibleEmail();
				complianceEventsTmp.add(complianceEvent);				
			}else if(tmpAccEmail.equalsIgnoreCase(complianceEvent.getAccountableEmail()) && tmpRspEmail.equalsIgnoreCase(complianceEvent.getResponsibleEmail())) {
				complianceEventsTmp.add(complianceEvent);
			}else {
				sendEmail( to,  null,  bcc,  environment.getRequiredProperty("email.from"),subject, getEmailDueComplianceTemplate(complianceEventsTmp, "TMPLT2"));
				complianceEventsTmp= new ArrayList<>(); to = new ArrayList<String>(); 
				to.add(complianceEvent.getAccountableEmail()); to.add(complianceEvent.getResponsibleEmail());
				tmpAccEmail=complianceEvent.getAccountableEmail(); 
				tmpRspEmail=complianceEvent.getResponsibleEmail();
				complianceEventsTmp.add(complianceEvent);
			}i++;
			if(i== complianceEvents.size()) {
				sendEmail( to,  null,  bcc,  environment.getRequiredProperty("email.from"),subject, getEmailDueComplianceTemplate(complianceEventsTmp, "TMPLT2"));
			}			
		} */
		return sendStatus;
	}
	
	public String sendEmailOnCompliance(Integer legalEntityCode, Integer comlianceEventId) throws Exception{
		logger.info("sendEmailOnCompliance .."+ legalEntityCode +" comlianceEventId.. "+ comlianceEventId);
		String sendStatus="Success";
		/*try {
			ComplianceEvent complianceEvent= complianceEventService.getComplianceEventById(legalEntityCode, comlianceEventId);
			List<String> to = new ArrayList<String>(); to.add(complianceEvent.getMonitorEmail());
			List<String> cc = new ArrayList<String>(); cc.add(complianceEvent.getAccountableEmail()); cc.add(complianceEvent.getResponsibleEmail());
			List<String> bcc = new ArrayList<String>();
			String subject=environment.getRequiredProperty("email.subject_on_compliance");
			sendEmail( to,  cc,  bcc,  environment.getRequiredProperty("email.from"),subject, getEmailOnComplianceTemplate(complianceEvent,"TMPLT3"));
			//sendEmail( to,  cc,  bcc,  "anilkumar.chintala@caprusit.com",subject, getEmailOnComplianceTemplate(complianceEvent));
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}*/
		return sendStatus;
	}
	
	/* public String getEmailDueComplianceTemplate(List<ComplianceEvent> complianceEvents,String templateType) {
		StringBuilder template= new StringBuilder();
		template.append("<html><head>"
                + "<style> table, th, td { border: 1px solid black; padding: 0px;} table{ border-spacing: 0px;}</style></head>"
                + "<body>"
                + "<table style=\"width:100%\">");
		
            logger.info("in results...");
	            template.append("<tr>");
	            template.append("<th>");   template.append("Regulator");   template.append("</th>");
	            template.append("<th>");   template.append("Reference");   template.append("</th>");
	            template.append("<th>");   template.append("Regulation");  template.append("</th>");
	            template.append("<th>");   template.append("Due Date");    template.append("</th>");
	            template.append("<th>");   template.append("Accountable");    template.append("</th>");
	            template.append("<th>");   template.append("Responsible");    template.append("</th>");
	            template.append("<th>");   template.append("Monitor");    template.append("</th>");
	            template.append("<tr>");
	       
	           for(ComplianceEvent complianceEvent: complianceEvents) {
		            template.append("<tr>");
		            template.append("<td style=\"padding:4px\">");   template.append(complianceEvent.getRegulator());   template.append("</td>");
		            template.append("<td style=\"padding:4px\">");   template.append(complianceEvent.getReference());   template.append("</td>");
		            template.append("<td style=\"padding:4px\">");   template.append(complianceEvent.getRegulation());  template.append("</td>");
		            template.append("<td style=\"padding:4px\">");   template.append(BankAuditUtil.parseDateToString(complianceEvent.getDueDate()));    template.append("</td>");
		            template.append("<td style=\"padding:4px\">");   template.append(complianceEvent.getAccountableRole());  template.append("</td>");
		            template.append("<td style=\"padding:4px\">");   template.append(complianceEvent.getResponsibleRole());  template.append("</td>");
		            template.append("<td style=\"padding:4px\">");   template.append(complianceEvent.getMonitorRole());  template.append("</td>");
		            template.append("<tr>");
	           }
	        template.append("</table>");
	        
	        template.append("<p>");
	        //template.append("This is a system generated mail. Do not reply this mail");
	        template.append(environment.getRequiredProperty("email.no_reply_mail_content"));
	        template.append("</body></html>");
		
		return template.toString();
	}
	
	public String getEmailOnComplianceTemplate(ComplianceEvent complianceEvent,String templateType) {
		StringBuilder template= new StringBuilder();
		template.append("<html><head>"
                + "<style> table, th, td { border: 1px solid black; padding: 0px;} table{ border-spacing: 0px;}</style></head>"
                + "<body>"
                + "<table style=\"width:100%\">");
		
            logger.info("in results...");
	            template.append("<tr>");
	            template.append("<th>");   template.append("Regulator");   template.append("</th>");
	            template.append("<th>");   template.append("Reference");   template.append("</th>");
	            template.append("<th>");   template.append("Regulation");  template.append("</th>");
	            template.append("<th>");   template.append("Due Date");    template.append("</th>");
	            template.append("<th>");   template.append("Accountable");    template.append("</th>");
	            template.append("<th>");   template.append("Responsible");    template.append("</th>");
	            template.append("<th>");   template.append("Monitor");    template.append("</th>");
	            template.append("<th>");   template.append("complied on");    template.append("</th>");
	            template.append("<tr>");
	       
	            template.append("<tr>");
	            template.append("<td style=\"padding:4px\">");   template.append(complianceEvent.getRegulator());   template.append("</td>");
	            template.append("<td style=\"padding:4px\">");   template.append(complianceEvent.getReference());   template.append("</td>");
	            template.append("<td style=\"padding:4px\">");   template.append(complianceEvent.getRegulation());  template.append("</td>");
	            template.append("<td style=\"padding:4px\">");   template.append(BankAuditUtil.parseDateToString(complianceEvent.getDueDate()));    template.append("</td>");
	            template.append("<td style=\"padding:4px\">");   template.append(complianceEvent.getAccountableRole());  template.append("</td>");
	            template.append("<td style=\"padding:4px\">");   template.append(complianceEvent.getResponsibleRole());  template.append("</td>");
	            template.append("<td style=\"padding:4px\">");   template.append(complianceEvent.getMonitorRole());  template.append("</td>");
	            template.append("<td style=\"padding:4px\">");   template.append(BankAuditUtil.parseDateToString(complianceEvent.getExecution_date()));  template.append("</td>");
	            template.append("<tr>");
	        
	        template.append("</table>");
	        
	        template.append("<p>");
	        //template.append("This is a system generated mail. Do not reply this mail");
	        template.append(environment.getRequiredProperty("email.no_reply_mail_content"));
	        template.append("</body></html>");
		
		return template.toString();
	}
	*/
	
	/*************************************** Email template for Nabard CRAR, Start here  *******************************************/
	
	/*
	public void sendEmail(String emailId,String token) {
		String body="Hi, </br> \\n Please use below Token Number to Change Password ";
		body+="</br> \\n";
		body+="Token : "+token;
		body+="</br> \\n";
		body+=" This is a system-generated e-mail regarding your BAAS Password Reset, please don't reply to this message.";
		
		MailSender mailSender= emailConfig.javaMailSender();
        SimpleMailMessage message = new SimpleMailMessage();
		message.setTo(emailId);
        message.setSubject("Bank Audit:");
        message.setText(body);
        mailSender.send(message);
	}
	*/
	
	/******************************************* Email template for User password reset *******************************************/
	public void sendEmailWithTokenForResetPwd(Integer legalEntityCode, String emailId, String token) throws InvalidToListException{
		logger.info("Inside sendEmailWithTokenForResetPwd .. LE.."+ legalEntityCode+" cc.."+emailId+" token.."+token+" from.."+environment.getRequiredProperty("email.from"));
		
		try {
			
			if (emailId==null || "".equals(emailId.trim())) {
				throw new InvalidToListException("To list should not be empty");
			}
			MimeMessage message = new MimeMessage(getsession());
			message.setFrom(new InternetAddress(environment.getRequiredProperty("email.from")));
			
			List<String> to = new ArrayList<String>(); to.add(emailId);
			for (String x : to) message.addRecipient(Message.RecipientType.TO, new InternetAddress(x)); // to list
			//if(cc !=null) for (String x : cc) message.addRecipient(Message.RecipientType.CC, new InternetAddress(x));	// cc list		
			//if(bcc!=null)for (String x : bcc) message.addRecipient(Message.RecipientType.BCC, new InternetAddress(x)); // bcc list
			
			String template=EmailTemplates.getRestPwdTokenTemplate(null, token);
			
			message.setSubject("Supersoft :Token for reset the password");
	        message.setContent(template.toString(), "text/html");
		        //message.setContent("<h1>This is actual message embedded in HTML tags</h1>", "text/html");
			Transport.send(message);
			logger.info("===== Email send =====");
		} catch (MessagingException mex) {
			mex.printStackTrace();
		}
	}
	
	/******************************************* User password reset, end here ****************************************************/
}

class InvalidToListException extends Exception {

	private static final long serialVersionUID = 1L;

	InvalidToListException(String s) {
		super(s);
	}
}
