var nodemailer = require('nodemailer');
var config = require('./config.js');
var template = require('./template.js');
var database = require('./database.js');

/**
 * Mail module
 */
module.exports = {
    transporter: null,
    /**
     * Load mail config.
     */
    init: function() {
        if (process.env.NODE_ENV == 'test')
            return;

        this.transporter = nodemailer.createTransport(config.smtp);

        this.transporter.verify(function(error, success) {
            if (error) {
                console.error(error);
            } else if (config.app.debug) {
                console.log('SMTP connection stablished');
            }
        });

    },

    /**
     * Send email.
     * @param {Object} recipient - Mail destinatary
     * @param {String} subject - Subject
     * @param {String} body - Mail body
     * @param {Object} attachments - Mail attachments
     * @param {Object} params - Params
     * @param {Object} cb - Callback
     */
    send: function(recipient, subject, body, attachments, params, cb) {
        if (process.env.NODE_ENV == 'test')
            return;

        let mailOptions = {
            from: '"' + config.app.senderName + '" <' + config.app.senderMail + '>',
            to: recipient,
            subject: subject,
            html: body,
            attachments
        };

        if (process.env.NODE_ENV != 'production')
            mailOptions.to = config.smtp.testEmail;

        this.transporter.sendMail(mailOptions, (error, info) => {
            try {
                let status = (error ? error.message : 'OK');
                this.log(params.sender, params.recipient, recipient, subject, body, params.message, status);

                if (error)
                    return cb(new Error('Email not sent: ' + error));

                if (config.app.debug)
                    console.log('Mail sent ' + info.messageId + ' [' + info.response + ']');

                cb();
            } catch (e) {
                throw e;
            }
        });
    },

    /**
     * Send email with template.
     * @param {String} tplName - Template name
     * @param {Object} params - Params object
     * @param {Object} cb - Callback
     */
    sendWithTemplate: function(tplName, params, cb) {
        template.get(tplName, params, (error, result) => {
            if (error)
                return cb(error);

            // Custom attachments
            if (params.attachments)
                params.attachments.forEach(function(attachment) {
                    result.attachments.push(attachment);
                });

            this.send(result.recipient, result.subject, result.body, result.attachments, params, error => {
                if (error)
                    return cb(error);

                cb();
            });
        });
    },

    /**
     * Add mail log
     * @param {Integer} senderId - Sender id
     * @param {Integer} recipientId - Recipient id
     * @param {String} sender - Sender email
     * @param {String} subject - Mail subject
     * @param {String} body - Mail body
     * @param {String} plainTextBody - Mail plain text body
     * @param {String} status - Mail status
     */
    log: function(senderId, recipientId, sender, subject, body, plainTextBody, status) {
        let qry = `INSERT INTO mail(senderFk, recipientFk, sender, replyTo, subject, body, plainTextBody, sent, status) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`;
        let qryParams = [senderId, recipientId, sender, config.app.senderMail, subject, body, plainTextBody, 1, status];

        database.pool.query(qry, qryParams, function(error, result) {
            if (config.app.debug && error)
                console.log('Mail log: ' + error);
        });
    }
};