'use strict';

const globalHooks = require('../../../hooks');
const hooks = require('feathers-hooks');
const auth = require('feathers-authentication');

const restrictToCurrentSchool = globalHooks.ifNotLocal(globalHooks.restrictToCurrentSchool);

exports.before = {
	all: [auth.hooks.authenticate('jwt')],
	find: [restrictToCurrentSchool],
	get: [],
	create: [],
	update: [restrictToCurrentSchool],
	patch: [restrictToCurrentSchool],
	remove: [restrictToCurrentSchool]
};

exports.after = {
	all: [],
	find: [],
	get: [globalHooks.ifNotLocal(globalHooks.denyIfNotCurrentSchool({errorMessage: 'Die angefragte Gruppe gehört nicht zur eigenen Schule!'}))],
	create: [],
	update: [],
	patch: [],
	remove: []
};

@@ -149,100 +149,1212 @@
 ');%0A
-%0Aconst restrictToCurrentSchool = globalHooks.ifNotLocal(globalHooks.restrictToCurrentSchool)
+const _ = require('lodash');%0Aconst ClassModel = require('../model').classModel;%0Aconst CourseModel = require('../model').courseModel;%0A%0Aconst restrictToCurrentSchool = globalHooks.ifNotLocal(globalHooks.restrictToCurrentSchool);%0A%0A/**%0A * adds all students to a course when a class is added to the course%0A * @param hook - contains created/patched object und request body%0A */%0Aconst addWholeClassToCourse = (hook) =%3E %7B%0A%09let requestBody = hook.data;%0A%09let course = hook.result;%0A%09if ((requestBody.classIds %7C%7C %5B%5D).length %3E 0) %7B // just courses do have a property %22classIds%22%0A%09%09return Promise.all(requestBody.classIds.map(classId =%3E %7B%0A%09%09%09return ClassModel.findById(classId).exec().then(c =%3E  c.userIds);%0A%09%09%7D)).then(studentIds =%3E %7B%0A%09%09%09// flatten deep arrays and remove duplicates%0A%09%09%09studentIds = _.uniqWith(_.flattenDeep(studentIds), (e1, e2) =%3E JSON.stringify(e1) === JSON.stringify(e2));%0A%0A%09%09%09// add all students of classes to course, if not already added%0A%09%09%09return Promise.all(studentIds.map(s =%3E %7B%0A%09%09%09%09if (course.userIds.indexOf(s) %3C 0) %7B%0A%09%09%09%09%09return CourseModel.update(%7B_id: course._id%7D, %7B$push: %7BuserIds: s%7D%7D).exec();%0A%09%09%09%09%7D else %7B%0A%09%09%09%09%09return %7B%7D;%0A%09%09%09%09%7D%0A%09%09%09%7D)).then(_ =%3E hook);%0A%09%09%7D);%0A%09%7D else %7B%0A%09%09return hook;%0A%09%7D%0A%7D
 ;%0A%0Ae
@@ -1761,32 +1761,53 @@
 %7D))%5D,%0A%09create: %5B
+addWholeClassToCourse
 %5D,%0A%09update: %5B%5D,%0A
@@ -1815,16 +1815,37 @@
 patch: %5B
+addWholeClassToCourse
 %5D,%0A%09remo

add hook that add all class' students to a course (#220)