package eu.dnetlib.common.utils.mail;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Date;

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class EmailMessage {

	private static final Log log = LogFactory.getLog(EmailMessage.class);

	private final MimeMessage mimeMessage;

	protected EmailMessage(final Session session, final String subject, final String content, final String fromMail, final String fromName, final String to,
		final String... ccs)
		throws MessagingException, UnsupportedEncodingException, AddressException {

		this.mimeMessage = new MimeMessage(session);

		this.mimeMessage.setFrom(new InternetAddress(fromMail, fromName));
		this.mimeMessage.setSubject(subject);
		this.mimeMessage.setContent(content, "text/html; charset=utf-8");
		this.mimeMessage.setSentDate(new Date());

		this.mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

		for (final String cc : ccs) {
			this.mimeMessage.addRecipient(Message.RecipientType.CC, new InternetAddress(cc));
		}
	}

	public void sendMailAsync() {
		final Thread t = new Thread(() -> sendMail());
		t.start();
	}

	public void sendMail() {
		try {
			log.info("Sending mail to " + Arrays.toString(mimeMessage.getAllRecipients()) + "...");
			Transport.send(this.mimeMessage);
			log.info("...sent");
		} catch (final MessagingException e) {
			log.error("Error sending mail", e);
		}
	}
}
