package com.agilex.vamf.missionhealth.message;

import com.agilex.messaging.core.MessageHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;

public class EmailNotificationMessageHandler implements MessageHandler<EmailNotificationMessage> {
    private final static Log logger = LogFactory.getLog(EmailNotificationMessageHandler.class);

    private static JavaMailSender mailSender;

    public EmailNotificationMessageHandler(JavaMailSender missionHealthMailSender){
        logger.debug(this.getClass().getName() + " ctor");
        if (mailSender == null){
            logger.debug("MessagingFactory.getJavaMailSender()");
            mailSender = missionHealthMailSender;
        }
        
    }
    @Override
    public void handle(EmailNotificationMessage message) {

        logger.debug("Received " + message.getClass().getName());
       /* if (mailSender == null){
            logger.debug("MessagingFactory.getJavaMailSender()");
            mailSender = MessagingFactory.getJavaMailSender();
        }*/

        try {
            sendEmail(message);

        } catch (MailException e) {
            logger.error("Unable to send email");
            logger.debug(e.getMessage());
            throw e;
        }
    }

    private void sendEmail(EmailNotificationMessage message) {
        logger.debug(this.getClass().getName() + ": Sending email");
        logger.debug("To: " + message.getEmailAddress());
        logger.debug("Body: " + message.getMessageBody());


        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom(message.getFromAddress());
        mailMessage.setReplyTo(message.getToAddress());
        mailMessage.setTo(message.getEmailAddress());
        mailMessage.setSubject(message.getSubject());
        mailMessage.setText(message.getMessageBody());
        mailSender.send(mailMessage);
        logger.debug("Email Sent");
    }
}
