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.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


@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 {
        List<String> imageSources = parseImages(mail.getContent());
        List<String> cids = new ArrayList<>();
        if (!imageSources.isEmpty()) {
            for (int i = 0; i < imageSources.size(); i++) {
                cids.add(UUID.randomUUID().toString());
            }
            mail.setContent(replaceImageSources(mail.getContent(), cids));
        }
        MimeMultipart content = new MimeMultipart("related");
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(mail.getContent(), "text/html; charset=UTF-8");
        content.addBodyPart(messageBodyPart);
        if (!imageSources.isEmpty()) {
            for (int i =0; i < imageSources.size(); i++) {
                MimeBodyPart imagePart = new MimeBodyPart();
                try {
                    imagePart.attachFile(applicationContext.getResource(imageSources.get(i)).getFile());
                    imagePart.setContentID("<" + cids.get(i) + ">");
                    imagePart.setDisposition(MimeBodyPart.INLINE);
                    content.addBodyPart(imagePart);
                } catch (IOException | MessagingException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
        MimeMessage message = this.emailSender.createMimeMessage();
        message.setSubject(mail.getSubject());
        message.setContent(content);
        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");
            inputStream.close();
            return writer.toString();
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        return "";
    }

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

    private List<String> parseImages(String content) {
        List<String> imagePaths = new ArrayList<>();

        int lastIndex = 0;

        while (lastIndex != -1) {
            lastIndex = content.indexOf("img src=\"", lastIndex);

            if (lastIndex != -1) {
                imagePaths.add(content.substring(lastIndex + 9, content.indexOf("\"", lastIndex + 9)));
                lastIndex ++;
            }
        }

        return imagePaths;
    }

    private String replaceImageSources(String content, List<String> cids) {

        int lastIndex = 0;
        int cidIndex = 0;

        while (lastIndex != -1) {
            lastIndex = content.indexOf("img src=\"", lastIndex);

            if (lastIndex != -1) {
                content = content.replace(content.substring(lastIndex + 9, content.indexOf("\"", lastIndex + 9)), "cid:" + cids.get(cidIndex));
                lastIndex ++;
                cidIndex ++;
            }
        }

        return content;
    }
}
