/**
 * Paypal classic API with NVP formatting
 * @ndaidong
 * Refer: https://developer.paypal.com/docs/classic/api/
 **/

var bella = require('bellajs');
var request = require('request');
var Promise = require('bluebird');

var version = 124;
var liveAPIBase = 'https://api-3t.paypal.com/nvp';
var sandboxAPIBase = 'https://api-3t.sandbox.paypal.com/nvp';

var stringify = (data) => {
  var s = '';
  if(bella.isString(data)){
    s = data;
  }
  else if(bella.isArray(data) || bella.isObject(data)){
    var ar = [];
    for(var k in data){
      var val = data[k];
      if(bella.isString(val)){
        val = bella.encode(val);
      }
      else if(bella.isArray(val) || bella.isObject(val)){
        val = JSON.stringify(val);
      }
      ar.push(bella.encode(k) + '=' + val);
    }
    if(ar.length > 0){
      s = ar.join('&');
    }
  }
  return s;
}

var parse = (s) => {
  if(!bella.isString(s)){
    return s;
  }

  var d = {};
  var ss = bella.decode(s);
  var a = ss.split('&');
  if(a.length > 0){
    a.forEach(function(item){
      var b = item.split('=');
      if(b.length === 2){
        d[b[0]] = b[1];
      }
    });
  }
  return d;
}

function Paypal(opts){
  var mode = opts.mode || 'sandbox';
  var username = opts.username || '';
  var password = opts.password || '';
  var signature = opts.signature || '';

  var baseURL = mode === 'live' ? liveAPIBase : sandboxAPIBase;

  var payload = {
    USER: username,
    PWD: password,
    SIGNATURE: signature,
    VERSION: version
  }

  var sendRequest = function(method, params){
    var o = bella.copies(payload, params);
    o.METHOD = method;
    return new Promise(function(resolve, reject){
      return request.post({
        url: baseURL,
        headers: {
          'X-PAYPAL-SECURITY-USERID': o.USER,
          'X-PAYPAL-SECURITY-PASSWORD': o.PWD,
          'X-PAYPAL-SECURITY-SIGNATURE': o.SIGNATURE,
          'X-PAYPAL-RESPONSE-DATA-FORMAT': 'JSON'
        },
        body: stringify(params)
      }, function(err, response, body){
        if(err){
          console.trace(err);
          return reject(err);
        }
        var r = parse(body);
        return resolve(r);
      });
    });
  }
  return {
    request: sendRequest
  }
}


module.exports = Paypal;

@@ -1154,16 +1154,308 @@
 n d;%0A%7D%0A%0A
+var toCurrency = function(n)%7B%0A  return n.toFixed(2).replace(/./g, (c, i, a) =%3E %7B%0A    return i && c !== '.' && ((a.length - i) %25 3 === 0) ? ',' + c : c;%0A  %7D);%0A%7D%0A%0Avar formatCurrency = function(num)%7B%0A  if(!num %7C%7C !bella.isNumber(num))%7B%0A    return '$0.00';%0A  %7D%0A  return '$' + toCurrency(num);%0A%7D%0A%0A
 function
@@ -2508,16 +2508,52 @@
 dRequest
+,%0A    formatCurrency: formatCurrency
 %0A  %7D%0A%7D%0A%0A

Add formatCurrency