// Envoi des e-mails en version HTML + txt
const nodemailer = require("nodemailer");
const pug = require("pug");

const config = require("../config/main.js");
const configMail = require("../config/mail.js");
const configTpl = require("../views/"+config.theme+"/config/"+config.availableLangs[0]+".js");

class ToolMail
{
    static async sendMail(stmpId, recipients, subject, mailText, mailHTML, mailDatas)
    {        
        let transporter = nodemailer.createTransport(
        {
            host: configMail.SMTP.hosts[stmpId],
            port: parseInt(configMail.SMTP.ports[stmpId], 10),
            secure: (configMail.SMTP.secures[stmpId]==="true") ? true : false,
            auth:
            {
                user: configMail.SMTP.logins[stmpId],
                pass: configMail.SMTP.passwords[stmpId]
            }
        });

        let html;
        if(mailDatas!==undefined)
        {
            mailDatas.siteUrl=config.siteUrl;
            mailDatas.mailRecipientTxt=configTpl.mailRecipientTxt;
            mailDatas.footLinks=configTpl.footLinks;
            const compiledFunction = pug.compileFile("./views/"+config.theme+"/mail.pug");
            html=await compiledFunction(mailDatas);
        }
        else if(mailHTML!=="")
            html=mailHTML;
        const info=await transporter.sendMail(
        {
            from: '"'+configMail.SENDER.name+'" <'+configMail.SENDER.email+'>',
            to: recipients,
            subject: subject,
            text: mailText,
            html: html
        });
        return info;
    }
}

module.exports = ToolMail;