package eu.eudat.logic.services.utilities;

import eu.eudat.models.data.mail.SimpleMail;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.*;


@Service("mailService")
public class MailServiceImpl implements MailService {
    private static final Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);

    private Environment env;

    private JavaMailSender emailSender;

    private ApplicationContext applicationContext;

    @Autowired
    public MailServiceImpl(Environment env, JavaMailSender emailSender, ApplicationContext applicationContext) {
        this.env = env;
        this.emailSender = emailSender;
        this.applicationContext = applicationContext;
    }

    @Override
    public void sendSimpleMail(SimpleMail mail) throws MessagingException {
        MimeMessage message = this.emailSender.createMimeMessage();
        message.setSubject(mail.getSubject());
        message.setText(mail.getContent(), "utf-8", "html");
        message.addRecipients(Message.RecipientType.TO, mail.getTo());
        message.setFrom(env.getProperty("mail.from"));
        this.emailSender.send(message);
    }

    public Environment getEnv() {
        return env;
    }

    @Override
    public String getMailTemplateContent(String resourceTemplate)  {
        Resource resource = applicationContext.getResource(resourceTemplate);
        try {
            InputStream inputStream = resource.getInputStream();
            StringWriter writer = new StringWriter();
            IOUtils.copy(inputStream, writer, "UTF-8");
            return writer.toString();
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        return "";
    }

    @Override
    public String getMailTemplateSubject() {
        return env.getProperty("mail.subject");
    }
}
