package com.agilex.healthcare.schedulingmanager.notification.appointmentrequest;

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;


/**
 * Created with IntelliJ IDEA.
 * User: clarkee
 * Date: 2/25/13
 * Time: 10:37 AM
 * Message handler responsible for sending email given details from EmailNotificationMessage.
 * Uses configured JavaMailSender
 */
public class EmailNotificationMessageHandler implements MessageHandler<EmailNotificationMessage> {
    private final static Log logger = LogFactory.getLog(EmailNotificationMessageHandler.class);

    private static JavaMailSender mailSender;

    public EmailNotificationMessageHandler(){
        logger.debug(this.getClass().getName() + " ctor");
    }
    @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.info("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.getFrom());
        mailMessage.setReplyTo(message.getReplyTo());
        mailMessage.setTo(message.getEmailAddress());
        mailMessage.setSubject(message.getSubject());
        mailMessage.setText(message.getMessageBody());
        mailSender.send(mailMessage);
        logger.debug("Email Sent");
    }
}

