'use strict';

// nitty gritty //
var express = require('express');
var braintree = require('braintree');
var router = express.Router(); // eslint-disable-line new-cap
var gateway = require('../lib/gateway');

var TRANSACTION_SUCCESS_STATUSES = [
  braintree.Transaction.Status.Authorizing,
  braintree.Transaction.Status.Authorized,
  braintree.Transaction.Status.Settled,
  braintree.Transaction.Status.Settling,
  braintree.Transaction.Status.SettlementConfirmed,
  braintree.Transaction.Status.SettlementPending,
  braintree.Transaction.Status.SubmittedForSettlement
];

function formatErrors(errors) {
  var formattedErrors = '';

  for (var i in errors) { // eslint-disable-line no-inner-declarations, vars-on-top
    if (errors.hasOwnProperty(i)) {
      formattedErrors += 'Error: ' + errors[i].code + ': ' + errors[i].message + '\n';
    }
  }
  return formattedErrors;
}

function createResultObject(transaction) {
  var result;
  var status = transaction.status;

  if (TRANSACTION_SUCCESS_STATUSES.indexOf(status) !== -1) {
    result = {
      header: 'Sweet Success!',
      icon: 'success',
      message: 'Your test transaction has been successfully processed. See the Braintree API response and try again.'
    };
  } else {
    result = {
      header: 'Transaction Failed',
      icon: 'fail',
      message: 'Your test transaction has a status of ' + status + '. See the Braintree API response and try again.'
    };
  }

  return result;
}

router.get('/', function (req, res) {
  res.redirect('/checkouts/new');
});

router.get('/checkouts/new', function (req, res) {
  gateway.clientToken.generate({}, function (err, response) {
    res.render('checkouts/new', {clientToken: response.clientToken, messages: req.flash('error')});
  });
});

router.get('/checkouts/:id', function (req, res) {
  var result;
  var transactionId = req.params.id;

  gateway.transaction.find(transactionId, function (err, transaction) {
    result = createResultObject(transaction);
    res.render('checkouts/show', {transaction: transaction, result: result});
  });
});

router.post('/checkouts', function (req, res) {
  var transactionErrors;
  var amount = req.body.amount; // In production you should not take amounts directly from clients
  var nonce = req.body.payment_method_nonce;
  var cardholderName = req.body.cardholderName;
  var startDate = new Date(Date.UTC(2016, 9, 6, 0, 0, 0));

  // gateway.subscription.create({
  //   paymentMethodNonce: nonce,
  //   planId: "four_month_membership_id",
  //   firstBillingDate: startDate
  // }, function (err, result) {
  //   result.success;
  // });
  
  gateway.transaction.sale({
  amount: amount,
  paymentMethodNonce: nonce,
  customer: {
    firstName: "Drew",
    lastName: "Smith",
    company: "Braintree",
    phone: "312-555-1234",
    fax: "312-555-12346",
    website: "http://www.example.com",
    email: "drew@example.com",
    planId: "four_month_membership_id"
  },
  billing: {
    firstName: "Paul",
    lastName: "Smith",
    company: "Braintree",
    streetAddress: "1 E Main St",
    extendedAddress: "Suite 403",
    locality: "Chicago",
    region: "IL",
    postalCode: "60622",
    countryCodeAlpha2: "US"
  },
  options: {
    storeInVaultOnSuccess: true
  },
}, function (err, result) {
    if (result.success || result.transaction) {
      res.redirect('checkouts/' + result.transaction.id);
    } else {
      transactionErrors = result.errors.deepErrors();
      req.flash('error', {msg: formatErrors(transactionErrors)});
      res.redirect('checkouts/new');
    }
});

  // gateway.transaction.sale({
  //   amount: amount,
  //   paymentMethodNonce: nonce
  // }, function (err, result) {
  //   if (result.success || result.transaction) {
  //     res.redirect('checkouts/' + result.transaction.id);
  //   } else {
  //     transactionErrors = result.errors.deepErrors();
  //     req.flash('error', {msg: formatErrors(transactionErrors)});
  //     res.redirect('checkouts/new');
  //   }
  // });
});

module.exports = router;

@@ -2636,16 +2636,19 @@
 sale(%7B%0A 
+ //
  amount:

Update index.js