package eu.dnetlib.uoaadmintools.emailSender;

import eu.dnetlib.uoaadmintools.configuration.properties.MailConfig;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.stereotype.Service;

import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.*;

@Service
@Configurable
public class EmailSender {

    private static final Logger logger = Logger.getLogger(EmailSender.class);

    @Autowired
    private MailConfig mailConfig;

    public boolean send(List<String> recipients, String subject, String body, Boolean bcc) {
        // Get system properties
        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", mailConfig.getHost());
        properties.put("mail.smtp.port", mailConfig.getPort());
        properties.put("mail.smtp.auth", mailConfig.getAuth()); //enable authentication
        properties.put("mail.smtp.starttls.enable", "true");
        logger.debug("Try to connect to mail sender with "+ mailConfig.getUsername());
        Session session = Session.getInstance(properties,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(mailConfig.getUsername(), mailConfig.getPassword());
                    }
                });

        try {
            logger.debug("Try to sent e-mail to "+recipients.toString()+
            "\nSubject: "+subject+
            "\nBody:"+body);

            // Create a default MimeMessage object.
            MimeMessage message = new MimeMessage(session);

            // Set From: header field of the header.
            message.setFrom(new InternetAddress(mailConfig.getFrom()));

            // Set To: header field of the header.
            if(!bcc) {
                for (String to : recipients) {
                    message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
                }
            }else{
                for (String to : recipients) {
                    message.addRecipient(Message.RecipientType.BCC, new InternetAddress(to));
                }
            }

            message.addRecipient(Message.RecipientType.BCC, new InternetAddress("openaire.test@gmail.com"));

            // Set Subject: header field
            message.setSubject(subject);

            // For simple text setText() can be used instead of setContent()

            // Send the actual HTML message, as big as you like
            message.setContent(body, "text/html");

            // Send message
            Transport.send(message);
            logger.debug("Sent message successfully....\n");
            return true;
        } catch (AddressException ae) {
            logger.error("Email could not be send.", ae);
            return false;
        } catch (MessagingException me) {
            logger.error("Email could not be send.", me);
            return false;
        }
    }

}
