var mongoose = require('mongoose');
var TreatmentPrescription = mongoose.model('TreatmentPrescription', require('../models/TreatmentPrescription').TreatmentPrescriptionSchema);

function 
(response, params){
	TreatmentPrescription.find(params)
		.sort('created_at')
		.exec(function(error, prescriptions){
			if(error){
				console.log(error);
				prescriptions = [];
			}
			response.json(prescriptions);
		});
}

function create_from_body(request){
	return {
		doctor: request.user._id,
		treatment: request.param('treatment'),
		items: request.body.items
	};
}

exports.list = function(request, response){
	var params = { treatment: request.param('treatment') };
	list(response, params);
};

exports.single = function(request, response){
	if(request.param('prescription') === 'new')
	{
		response.json(new TreatmentPrescription({ treatment: request.param('treatment') }));
		return;
	}

	var params = { _id: request.param('prescription'), treatment: request.param('treatment') };
	TreatmentPrescription.findOne(params, function(error, prescription){
		if(error){
			console.log(error);
			prescription = null;
		}
		response.json(prescription);
	});
};


exports.create = function(request, response){
	var values = create_from_body(request);
	var treatment = new TreatmentPrescription(values);
	treatment.save(function(error, document){
		if(error || !document){
			response.json({ error: error });
		} else {
			response.json(document);
		}
	});
};

exports.edit = function(request, response){
	var values = create_from_body(request);
	TreatmentPrescription.findByIdAndUpdate(request.body._id, values, function(error, document){
		if(error){
			response.json({ error: error });
			return;
		}

		response.json(document);
	});
};

exports.remove = function(request, response){
	if(request.user.type === 'doctor'){
		TreatmentPrescription.findByIdAndRemove(request.param('prescription'), function(error){
			if(error){
				console.log(error);
				response.send(400);
				return;
			}

			response.send(200)
		});
	} else {
		response.send(200)
	}
};
list