"use strict";

const createTransport = require('nodemailer').createTransport,
  { timestamp } = require("./timestamp");

const transporter = createTransport({
  host: 'email.ketrenos.com',
  pool: true,
  port: 25
});

function sendMail(to, subject, message, cc) {
  let envelope = {
    subject: subject,
    from: 'Ketr.Ketran <james_ketran@ketrenos.com>',
    to: to || '',
    cc: cc || ''
  };

  /* If there isn't a To: but there is a Cc:, promote Cc: to To: */
  if (!envelope.to && envelope.cc) {
    envelope.to = envelope.cc;
    delete envelope.cc;
  }

  envelope.text = message
  envelope.html = message.replace(/\n/g, "<br>\n");

  return new Promise(function (resolve, reject) {
    let attempts = 10;

    function attemptSend(envelope) {
      /* Rate limit to ten per second */
      transporter.sendMail(envelope, function (error, info) {
        if (error) {
          if (attempts) {
            attempts--;
            console.warn(timestamp() + " Unable to send mail. Trying again in 100ms (" + attempts + " attempts remain): ", error);
            setTimeout(send.bind(undefined, envelope), 100);
          } else {
            console.error(timestamp() + " Error sending email: ", error)
            return reject(error);
          }
        }

        console.log(timestamp() + " Mail sent to: " + envelope.to);
        return resolve(true);
      });
    }

    attemptSend(envelope);
  }).then(function(success) {
    if (!success) {
      console.error(timestamp() + " Mail not sent to: " + envelope.to);
    }
  });
}

module.exports = {
  sendMail: sendMail
};
