import {Mongo} from "meteor/mongo";
import {Meteor} from "meteor/meteor";
import {Students} from "./students";
import {Staff} from "./staff";
import { Roles } from 'meteor/alanning:roles';

export const Sites = new Mongo.Collection('sites');

if (Meteor.isServer) {
	// This code only runs on the server
	Meteor.publish('sites', function() {
		return Sites.find({});
	});
}
Meteor.methods({
	'sites.update'(_id, name) {
		if(Roles.userIsInRole(Meteor.userId(), "admin", {anyScope:true})) {
			Sites.update({_id}, {$set: {name}});
		}
	},
	'sites.add'(name) {
		if(Roles.userIsInRole(Meteor.userId(), "admin", {anyScope:true})) {
			Sites.insert({name});
		}
	},
	'sites.remove'(_id) {
		if(Roles.userIsInRole(Meteor.userId(), "admin", {anyScope:true})) {
			let site = Sites.find({_id});

			if(site) {
				//Clear any site references in student/room entries.
				Students.update({siteId: _id}, {$unset: {siteId: 1}});
				Staff.update({siteId: _id}, {$unset: {siteId: 1}});
				Sites.remove({_id});
			}
		}
	},
});
