package info.bukova.isspst.mail;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.InputStreamSource;
import org.springframework.mail.MailAuthenticationException;
import org.springframework.mail.MailParseException;
import org.springframework.mail.MailSendException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;

public class MailerWithAttachement implements Mailer {
	
	private JavaMailSender sender;
	private String from;
	private boolean overrideFrom = false;
	private static final Logger logger = LoggerFactory.getLogger(MailerWithAttachement.class);
	
	public MailerWithAttachement(JavaMailSender sender) {
		this.sender = sender;
	}
	
	@Override
	@Async
	public void send(MailMessage message) {
		MimeMessage mimeMessage = sender.createMimeMessage();

		try {
			MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
			
			message.setReplyTo(message.getFrom());
			
			if (message.getFrom() == null || message.getFrom().isEmpty() || overrideFrom) {
				if (from == null || from.isEmpty()) {
					message.setFrom("tomcat@is.bukova.info");
				} else {
					message.setFrom(from);
				}
			}
			
			if (message.getReplyTo() == null) {
				message.setReplyTo(message.getFrom());
			}

			helper.setFrom(message.getFrom());
			helper.setReplyTo(message.getReplyTo());
			helper.setTo(message.getTo());
			helper.setSubject(message.getSubject());
			
			if (message.getText() != null) {
				helper.setText(message.getText(), message.isHtml());
			} else {
				helper.setText("", message.isHtml());
			}
			
			if (message.getAttachementData() != null) {
				InputStreamSource source = new  ByteArrayResource(message.getAttachementData());
				helper.addAttachment(message.getAttachementName(), source, message.getContentType());
			}
		} catch (MessagingException e) {
			throw new MailParseException(e);
		}
		try {
			sender.send(mimeMessage);
			logger.info("Mail queued for send");
		} catch (MailAuthenticationException e) {
			logger.error("Authentication error");
		} catch (MailSendException e) {
			logger.error("Mail send error: " + e.getMessage());
		}
		
	}

	public void setFrom(String from) {
		this.from = from;
	}
	
	public void setOverrideFrom(boolean override) {
		this.overrideFrom = override;
	}

}
