package ch.zhaw.gartenverwaltung.backgroundtasks.email;

import ch.zhaw.gartenverwaltung.Settings;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Class to send E-Mails
 */
public class EMailSender {

    /**
     * Method to send E-Mail to one or multiple recipients
     * @param recipients recipients E-Mail addresses separated by ";"
     * @param subject Subject of the E-Mail
     * @param text E-Mail message Text as rear text or html
     * @throws MessagingException If sending the E-Mail fails for any reason
     */
    public void sendMails(String recipients, String subject, String text) throws MessagingException {
        printMail(recipients, subject, text);
        MimeMessage message = new MimeMessage(Settings.getInstance().getSmtpCredentials().getSession());
        message.addHeader("Content-type", "text/HTML; charset=UTF-8");
        message.addHeader("format", "flowed");
        message.addHeader("Content-Transfer-Encoding", "8bit");
        message.setFrom(new InternetAddress(Settings.getInstance().getSmtpCredentials().fromAddress()));
        message.setReplyTo(InternetAddress.parse(Settings.getInstance().getSmtpCredentials().fromAddress(), false));
        message.setSubject(subject);
        message.setText(text);
        message.setSentDate(new Date());
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients, false));
        Transport.send(message);
    }

    private void printMail(String receiver, String subject, String text){
        System.out.printf("\nSending E-Mail:\nTo: %s\nSubject: %s\nMessage:\n%s\n", receiver, subject, text);
    }

}
