
/**
 * Module dependencies.
 */

var mongoose = require('mongoose')
var utils = require('../../lib/utils')
var extend = require('util')._extend
var User = mongoose.model('User');
var Donation = mongoose.model('Donation');
var config = require('config');
var razorNode = require("razornode");
var instance  = new razorNode(config.razor_key, config.razor_secret);


exports.load = function (req, res, next, donationId){
  Donation.load(donationId, function (err, article) {
    if (err) return next(err);
    if (!article) return next(new Error('not found'));
    req.donation = donation;
    next();
  });
};


exports.show = function (req, res) {
  return res.status(200).json(req.campaign);
};


exports.list = function (req, res) {
  var options = {
    criteria: {
      campaign: req.params.campaign
    }
  };

  Donation.list(options, function (err, donations) {
    if (err) res.status(500).json({ error: 'Something went wrong.' });

    res.status(200).json(campaigns);

  });
};


exports.create = function (req, res) {

  instance.capturePayment(req.body.razorpay_payment_id, req.body.amount)
    .then(function (result) {
      var donation = new Donation({
        owner: req.user._id,
        campaign: req.body.campaign,
        amount: req.body.amount/100
      });

      donation.save(function (err, donation) {
        if (err) return res.status(400).json({ error: err });

        res.status(200).json(donation);
      });

    }, function (err) {
      res.status(400).json({ error: err });
    });
};

/**
 * Update profile highlights
 */

exports.update = function (req, res){
  var profile = req.profile;

  extend(profile[req.params.profileSection], req.body);

  profile.save(function (err, result) {
    if (err) {
      return res.status(400).json({ error: err });
    }

    res.status(200).json(result);
  });
};


exports.upload_pic = function (req, res) {
  var image = req.files[0];
  var profile = req.profile;

  profile.uploadProfilePic(image, function (err) {
    if (err) {
      throw err;
    }

    res.status(200).json(profile);
  });
};
