'use strict';

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

/**
 * Create a infrastructureRequest
 */
exports.create = function (req, res) {
  var infrastructureRequest = new InfrastructureRequest(req.body);
  infrastructureRequest.user = req.user;
  var now = new Date().toString();
  infrastructureRequest.creation_date = now;

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

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

/**
 * Update a infrastructureRequest
 */
exports.update = function (req, res) {  
  var infrastructureRequest = req.infrastructureRequest;
  
  infrastructureRequest.requestSource = req.body.requestSource;
  infrastructureRequest.requestID = req.body.requestID;
  infrastructureRequest.note = req.body.note;
  infrastructureRequest.hostings = req.body.hostings;
  infrastructureRequest.otherRequests = req.body.otherRequests;
  
  infrastructureRequest.save(function (err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json(infrastructureRequest);
    }
  });
};

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

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

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

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

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