'use strict';

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

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

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

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

  attestation.business_unit_id = req.body.business_unit_id;
  attestation.department = req.body.department;
  attestation.statement = req.body.statement;
  attestation.date_start_string = req.body.date_start_string;
  attestation.date_end_string = req.body.date_end_string;
  attestation.response = req.body.response;
  attestation.originating_system_name = req.body.originating_system_name;
  attestation.originating_system_id = req.body.originating_system_id;
  
  attestation.save(function (err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json(attestation);
    }
  });
};

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

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

/**
 * List of Attestations
 */
exports.list = function (req, res) {
  Attestation.find().populate('user', 'displayName').exec(function (err, attestations) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json(attestations);
    }
  });
};

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

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