'use strict';

var Mailgun = require('mailgun-js');
var packageData = require('../package.json');

module.exports = function (options) {
  return new MailgunTransport(options);
};

function MailgunTransport(options) {
  this.options = options || {};
  this.name = 'Mailgun';
  this.version = packageData.version;

  this.mailgun = Mailgun({
    apiKey: this.options.auth.api_key,
    domain: this.options.auth.domain || ''
  });
}


MailgunTransport.prototype.send = function send(mail, callback) {
  var mailData = mail.data;
  // convert nodemailer attachments to mailgun-js attachements
  if(mailData.attachments){
    var a, b, aa = [];
    for(var i in mailData.attachments){
      a = mailData.attachments[i];
      b = new this.mailgun.Attachment({
        data        : a.path || undefined,
        filename    : a.filename || undefined,
        contentType : a.contentType || undefined,
        knownLength : a.knownLength || undefined
      });

      aa.push(b);
    }
    mailData.attachment = aa;

  }
  
  var options = {
    type       : mailData.type,
    to         : mailData.to,
    from       : mailData.from,
    subject    : mailData.subject,
    text       : mailData.text,
    html       : mailData.html,
    attachment : mailData.attachment
  }
  
  if( mailData.bcc ){
    options.bcc = mailData.bcc
  }

  this.mailgun.messages().send(options, function (err, data) {
    callback(err || null, data);
  });

};


@@ -624,16 +624,22 @@
 ar a, b,
+ data,
  aa = %5B%5D
@@ -719,89 +719,303 @@
 i%5D;%0A
+%0A
       
-b = new this.mailgun.Attachment(%7B%0A        data        : a.path %7C%7C undefined
+// mailgunjs does not encode content string to a buffer%0A      if (typeof a.content === 'string') %7B%0A        data = new Buffer(a.content, a.encoding);%0A      %7D else %7B%0A        data = a.content %7C%7C a.path %7C%7C undefined;%0A      %7D%0A%0A      b = new this.mailgun.Attachment(%7B%0A        data        : data
 ,%0A  

Add support for buffer and stringified buffer as attachment content