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

import java.util.ArrayList;
import java.util.List;

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;

import com.agilex.messaging.core.MessageHandler;

/**
 * Created with IntelliJ IDEA.
 * User: clarkee
 * Date: 2/28/13
 * Time: 9:15 AM
 * To change this template use File | Settings | File Templates.
 */
public class BatchEmailNotificationMessageHandler implements MessageHandler<BatchEmailNotificationMessage> {
    private final static Log logger = LogFactory.getLog(BatchEmailNotificationMessageHandler.class);
    private List<String> processedEmailsList = new ArrayList<String>();

    private JavaMailSender mailSender;

    public BatchEmailNotificationMessageHandler() {
        logger.debug(this.getClass().getName() + " ctor");
    }

    public BatchEmailNotificationMessageHandler(JavaMailSender mailSender) {
        this.mailSender = mailSender;
        logger.debug(this.getClass().getName() + " ctor");
    }

    @Override
    public void handle(BatchEmailNotificationMessage message) {
        logger.debug("Received " + message.getClass().getName());

        if (mailSender == null){
            logger.debug("MessagingFactory.getJavaMailSender()");
            mailSender = MessagingFactory.getJavaMailSender();
        }

        if (shouldSendNewEmail(message.getEmailAddress())){
            try {
                sendEmail(message);
                storeEmailEntry(message.getEmailAddress());

            } catch (MailException e) {
                logger.info("Unable to send email");
                logger.debug(e.getMessage());
                throw e;
            }
        }
        else{
            logger.debug("Not sending email due to Batch processing rules");
        }
    }

    protected void sendEmail(BatchEmailNotificationMessage 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");
    }

    private void storeEmailEntry(String emailAddress) {
        processedEmailsList.add(emailAddress);
    }

    private boolean shouldSendNewEmail(String emailAddress) {
        return !processedEmailsList.contains(emailAddress);
    }

    public void clearProcessedEmails() {
        processedEmailsList.clear();
    }
}