"use strict";

import { createTransport } from 'nodemailer';
import { timestamp } from "./timestamp";

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

function sendMail(to: string, subject: string, message: string, cc?: string): Promise<boolean> {
  let envelope: any = {
    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: any) {
      /* 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(() => attemptSend(envelope), 100);
          } else {
            console.error(timestamp() + " Error sending email: ", error)
            reject(error);
          }
        } else {
          console.log(timestamp() + " Mail sent to: " + envelope.to);
          resolve(true);
        }
      });
    }

    attemptSend(envelope);
  });
}

export {
  sendMail
};
