/*
 * Sending email
 * Created by: Michael Pastushkov <michael@pastushkov.com>
 */

'use strict';

const config = require('config');
const utils = require('./utils');
const nodemailer = require('nodemailer');
const Email = require('email-templates');

const transporter = nodemailer.createTransport(config.mailer);
  
function sendTemplate(to, template, locals) {

    let email = new Email({
        send: true,
        transport: config.mailer,
        preview: false
      });
      
    email
        .send({
          template: template,
          message: {
            from: config.mailer.from,
            replyTo: config.mailer.from,
            to: to
          },
          locals: locals
        })
        .then((m) => {
            utils.log(`Email sent to ${m.envelope.to}`);
            utils.log(m, 5);
        })
        .catch(utils.log_error);
}

function send(to, subj, text) {

    let mailOptions = {
        from: config.mailer.from,
        to: to,
        subject: subj,
        text: text
    };
      
    transporter.sendMail(mailOptions, function(error, info) {
        if (error) {
            console.log(error);
        } else {
            utils.log(`Email sent to : ${to}: ` + info.response);
        }
    });
}

module.exports.send = send;
module.exports.sendTemplate = sendTemplate;