'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	errorHandler = require('./errors.server.controller'),
	Profileaccess = mongoose.model('Profileaccess'),
	_ = require('lodash');

/**
 * Create a Profileaccess
 */
exports.create = function(req, res) {
	var profileaccess = new Profileaccess(req.body);
	profileaccess.user = req.user;

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

/**
 * Show the current Profileaccess
 */
exports.read = function(req, res) {
	res.jsonp(req.profileaccess);
};

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

	profileaccess = _.extend(profileaccess , req.body);

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

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

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

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

/**
 * Profileaccess middleware
 */
exports.profileaccessByID = function(req, res, next, id) { 
	Profileaccess.findById(id).populate('user', 'displayName').exec(function(err, profileaccess) {
		if (err) return next(err);
		if (! profileaccess) return next(new Error('Failed to load Profileaccess ' + id));
		req.profileaccess = profileaccess ;
		next();
	});
};

/**
 * Profileaccess authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
	if (req.profileaccess.user.id !== req.user.id) {
		return res.status(403).send('User is not authorized');
	}
	next();
};
