package eu.dnetlib.common.utils.mail;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;

import org.apache.commons.lang3.StringUtils;

import eu.dnetlib.common.exceptions.DnetException;

public class EmailFactory {

	private String smtpHost = "localhost";
	private int smtpPort = 587;
	private String smtpUser = null;
	private String smtpPassword = "";

	public EmailMessage prepareEmail(final String subject,
		final String content,
		final String fromMail,
		final String fromName,
		final String to,
		final String... ccs) throws DnetException {

		final Session session = Session.getInstance(obtainProperties(), obtainAuthenticator());

		try {
			return new EmailMessage(session, subject, content, fromMail, fromName, to, ccs);
		} catch (final Exception e) {
			throw new DnetException("Error preparing mail message", e);
		}
	}

	private Properties obtainProperties() {
		final Properties p = new Properties();
		p.put("mail.transport.protocol", "smtp");
		p.put("mail.smtp.host", getSmtpHost());
		p.put("mail.smtp.port", getSmtpPort());
		p.put("mail.smtp.auth", Boolean.toString(StringUtils.isNotBlank(getSmtpUser())));
		return p;
	}

	private Authenticator obtainAuthenticator() {
		if (StringUtils.isBlank(getSmtpUser())) { return null; }

		return new Authenticator() {

			private final PasswordAuthentication authentication =
				new PasswordAuthentication(getSmtpUser(), getSmtpPassword());

			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return authentication;
			}

		};
	}

	public String getSmtpHost() {
		return smtpHost;
	}

	public void setSmtpHost(final String smtpHost) {
		this.smtpHost = smtpHost;
	}

	public int getSmtpPort() {
		return smtpPort;
	}

	public void setSmtpPort(final int smtpPort) {
		this.smtpPort = smtpPort;
	}

	public String getSmtpUser() {
		return smtpUser;
	}

	public void setSmtpUser(final String smtpUser) {
		this.smtpUser = smtpUser;
	}

	public String getSmtpPassword() {
		return smtpPassword;
	}

	public void setSmtpPassword(final String smtpPassword) {
		this.smtpPassword = smtpPassword;
	}

}
