package ch.zhaw.gartenverwaltung.backgroundtasks.email;

import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import java.net.Authenticator;
import java.util.Properties;

/**
 * Class to store SMTP Credentials to send E-Mails and create
 * corresponding Session Object
 */
public record SmtpCredentials(
        String host,
        String port,
        String fromAddress,
        String username,
        String password,
        boolean startTLS
        ) {

    /**
     * Creates a Properties Object with SMTP Server Information
     * @return the created Properties Object
     */
    private Properties getProperties() {
        Properties properties = new Properties();
        properties.put("mail.smtp.host", host);
        properties.put("mail.smtp.port", port);
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", startTLS ? "true" : "false");
        return properties;
    }

    /**
     * Creates a javax.mail.Authenticator Object with username and password for SMTP Server
     * @return the created javax.mail.Authenticator Object
     */
    private javax.mail.Authenticator getAuthenticator() {
        return new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        };
    }

    /**
     * Method to get the Session Instance with the given SMTP Credentials
     * @return the Session Instance
     */
    public Session getSession() {
        return Session.getInstance(getProperties(), getAuthenticator());
    }
}
