import {Mongo} from "meteor/mongo";
import {Meteor} from "meteor/meteor";
import { check, Match } from 'meteor/check';
import { Roles } from 'meteor/alanning:roles';

//
// An asset type is a specific type of equipment.  Example: Lenovo 100e Chromebook.
//
export const Workshops = new Mongo.Collection('workshops');

if(Meteor.isServer) {
	// Drop any old indexes we no longer will use.  Create indexes we need.
	//try {Workshops._dropIndex("External ID")} catch(e) {}
	//Workshops.createIndex({name: "text"}, {name: "name", unique: false});
	//Workshops.createIndex({id: 1}, {name: "External ID", unique: true});

	//Debug: Show all indexes.
	// Workshops.rawCollection().indexes((err, indexes) => {
	// 	console.log(indexes);
	// });

	// This code only runs on the server
	Meteor.publish('workshops', function() {
		return Workshops.find({});
	});
}
Meteor.methods({
	'workshops.add'(name, description, signupLimit) {
		let signupSheet = [];
		
		check(name, String);
		check(description, String);
		// Match a positive integer or undefined/null.
		check(signupLimit, Match.Where((x) => {
			check(x, Match.Maybe(Match.Integer));
			return x ? x > 0 : true
		}))

		if(Roles.userIsInRole(Meteor.userId(), "admin", {anyScope:true})) {
			Workshops.insert({name, description, signupLimit, signupSheet});
		}
	},
	'workshops.update'(_id, name, description, signupLimit) {
		check(_id, String);
		check(name, String);
		check(description, String);
		// Match a positive integer or undefined/null.
		check(signupLimit, Match.Where((x) => {
			check(x, Match.Maybe(Match.Integer));
			return x ? x > 0 : true
		}))

		if(Roles.userIsInRole(Meteor.userId(), "admin", {anyScope:true})) {
			Workshops.update({_id}, {$set: {name, description, signupLimit}});
		}
	},
	'workshops.signup'(_id) {
		check(_id, String);
		
		if(Meteor.userId()) {
			let workshop = Workshops.findOne(_id);
			
			if(workshop) {
				if(!workshop.signupLimit || workshop.signedUp.length < workshop.signupLimit) {
					Workshops.update({_id}, {$push: {signupSheet: {_id: Meteor.userId()}}});
				}
			}
		}
	},
	'workshops.unsignup'(_id) {
		check(_id, String);

		if(Meteor.userId()) {
			let workshop = Workshops.findOne(_id);

			if(workshop) {
				Workshops.update({_id}, {$pull: {signupSheet: {_id: Meteor.userId()}}});
			}
		}
	},
	'workshops.complete'(_id) {
		check(_id, String);

		if(Roles.userIsInRole(Meteor.userId(), "admin", {anyScope:true})) {
			Workshops.update({_id}, {$set: {isComplete: true}})
		}
	},
	'workshops.remove'(_id) {
		check(_id, String);

		if(Roles.userIsInRole(Meteor.userId(), "admin", {anyScope:true})) {
			Workshops.remove({_id})
		}
	},
});

// console.log("Asset types setup.")
