package de.jottyfan.camporganizer.module.mail;

import java.nio.charset.StandardCharsets;
import java.util.Set;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Repository;

/**
 *
 * @author jotty
 *
 */
@Repository
public class MailRepository {

	private final static Logger LOGGER = LogManager.getLogger();

	@Autowired
	private JavaMailSender javaMailSender;

	@Value("${spring.mail.username}")
	private String username;

	/**
	 * Send an email with the message to the recipient. If email is blank, do
	 * nothing
	 *
	 * @param bean the mail
	 */
	public void sendMail(MailBean bean) {
		sendMail(bean.getTo(), bean.getSubject(), bean.getMessage());
	}

	/**
	 * Send an email with the message to the recipient. If email is blank, do
	 * nothing
	 *
	 * @param to      the email addresses
	 * @param subject the subject
	 * @param message the message
	 */
	private void sendMail(Set<String> to, String subject, String message) {
		if (to != null && to.size() > 0) {
			if (username != null && !username.isBlank()) {
				try {
					sendMail(to, subject, message, username);
				} catch (MessagingException e) {
					LOGGER.error(e.getMessage(), e);
				}
			} else {
				LOGGER.error("no email.username in configuration for sending emails");
			}
		} else {
			LOGGER.warn("no email address given, ignore informing the user about changes; message would have been: {}",
					message);
		}
	}

	/**
	 * send the email
	 *
	 * @param to      the recipients
	 * @param subject the subject
	 * @param message the message
	 * @param from    the username of the email account
	 * @throws MessagingException
	 */
	private void sendMail(Set<String> to, String subject, String message, String from) throws MessagingException {
		if (to == null || to.size() < 1) {
			throw new MessagingException("no recipient in " + to);
		}
		MimeMessage mimeMessage = javaMailSender.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED,
				StandardCharsets.UTF_8.name());
		helper.setFrom(from);
		helper.setSubject(subject);
		helper.setText(message, false);
		helper.setTo(to.toArray(new String[] {}));
		javaMailSender.send(mimeMessage);
	}

	/**
	 * for junit tests only
	 *
	 * @param javaMailSender the java mail sender
	 */
	protected void setJavaMailSender(JavaMailSender javaMailSender) {
		this.javaMailSender = javaMailSender;
	}

	/**
	 * for junit tests only
	 *
	 * @param username the username
	 */
	protected void setUsername(String username) {
		this.username = username;
	}
}
