///<reference path="../typing/nodemailer/nodemailer.d.ts"/>

import nodemailer = require('nodemailer');
import smtpTransport = require("nodemailer-smtp-transport");

var settings = require('settings');

/**
 * Service for mail.
 *
 * @class
 */
class MailService {
    /**
     * Transport.
     *
     * @private
     * @type {Transport}
     */
    private _transport: nodemailer.Transporter;

    /**
     * Constructor.
     *
     * @public
     * @constructors
     */
    public constructor() {
      var options: smtpTransport.SmtpOptions = {
        ignoreTLS: true,
        port: settings.smtp.port
      };

      this._transport = nodemailer.createTransport(options);
    }

    /**
     * Creates a mail options.
     *
     * @private
     * @param   {string} to         The recipient.
     * @param   {string} subject    The subject.
     * @param   {string} message    The message.
     * @return  {SendMailOptions}   The mail options.
     */
    private _createMailOptions = (to: string, subject: string, message: string): nodemailer.SendMailOptions => {
        return {
            from: settings.smtp.auth.user,
            to: to,
            subject: subject,
            html: message
        };
    }

    /**
     * Sends a e-mail.
     *
     * @public
     * @param {string}      to       The recipient.
     * @param {string}      subject  The subject.
     * @param {string}      message  The message.
     * @param {Function}    callback The callback.
     */
    public send = (to: string, subject: string, message: string, callback: (error: any) => void): void => {
        // Creates mail options.
        var mailOptions = this._createMailOptions(to, subject, message);

        // Send mail with defined transport object
        this._transport.sendMail(mailOptions, callback);
    }
}

export = new MailService();
