'use strict';

/**
 * Module dependencies.
 */
var path = require('path'),
  mongoose = require('mongoose'),
  Attestment = mongoose.model('Attestment'),
  errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));

/**
 * Create a attestment
 */
exports.create = function (req, res) {
  var attestment = new Attestment(req.body);
  attestment.user = req.user;
  var now = new Date().toString();
  attestment.attestment_date = now;
  
  attestment.save(function (err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json(attestment);
    }
  });
};

/**
 * Show the current attestment
 */
exports.read = function (req, res) {
  res.json(req.attestment);
};

/**
 * Update an attestment
 */
exports.update = function (req, res) {  
  var attestment = req.attestment;

  attestment.consumer_ID = req.body.consumer_ID;
  attestment.consumer_description = req.body.consumer_description;
  attestment.page_ID = req.body.page_ID;
  attestment.page_description = req.body.page_description;
  attestment.statements = req.body.statements;
  
  attestment.save(function (err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json(attestment);
    }
  });
};

/**
 * Add a new statement to existing attestment
 */
exports.addStatement = function (req, res) {
  var attestment = req.attestment;
    
  attestment.update(function (err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json(attestment);
    }
  });
};

/**
 * Delete an attestment
 */
exports.delete = function (req, res) {
  var attestment = req.attestment;

  attestment.remove(function (err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json(attestment);
    }
  });
};

/**
 * List of Attestments
 */
exports.list = function (req, res) {
  Attestment.find().sort('-created').populate('user', 'displayName').exec(function (err, attestments) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json(attestments);
    }
  });
};

/**
 * Attestment middleware
 */
exports.attestmentByID = function (req, res, next, id) {
  if (!mongoose.Types.ObjectId.isValid(id)) {
    return res.status(400).send({
      message: 'Attestment is invalid'
    });
  }

  Attestment.findById(id).populate('user', 'displayName').exec(function (err, attestment) {
    if (err) {
      return next(err);
    } else if (!attestment) {
      return res.status(404).send({
        message: 'No attestment with that identifier has been found'
      });
    }
    req.attestment = attestment;
    next();
  });
};
