import { Meteor } from 'meteor/meteor';
import { Roles } from 'meteor/alanning:roles';
import { check } from 'meteor/check';

// console.log("Setting Up Users...")

if (Meteor.isServer) {
	Meteor.publish(null, function() {
		if(this.userId) {
			return Meteor.roleAssignment.find({'user._id': this.userId});
		}
		else {
			this.ready();
		}
	});

	Meteor.publish(null, function() {
		return Meteor.roles.find({});
	});

	Meteor.publish("allUsers", function() {
		// console.log(Meteor.isServer);
		// console.log("AllUsers");
		// console.log("Meteor.userId(): " + Meteor.userId());
		// // console.log(Roles.userIsInRole(Meteor.userId(), "laptop-management"));
		// console.log(Meteor.roleAssignment.find({ 'user._id': Meteor.userId() }).fetch());
		// console.log(Roles.userIsInRole(Meteor.user(), "admin", {anyScope:true}));

		// Note: For some reason the {anyScope: true} is necessary on the server for the function to actually check roles.
		if(Roles.userIsInRole(Meteor.userId(), "admin", {anyScope:true})) {
			//console.log(Meteor.users.find({}).fetch());
			return Meteor.users.find({});
		}
		else {
			return [];
		}
	});
	Meteor.publish("allRoleAssignments", function() {
		// Note: For some reason the {anyScope: true} is necessary on the server for the function to actually check roles.
		if(Roles.userIsInRole(Meteor.userId(), "admin", {anyScope:true})) {
			return Meteor.roleAssignment.find({});
		}
		else {
			return [];
		}
	});

	Meteor.methods({
		'users.setUserRoles'(userId, roles) {
			if(Roles.userIsInRole(Meteor.userId(), "admin", {anyScope:true})) {
			    check(userId, String);
			    check(roles, Array);
				Roles.setUserRoles(userId, roles, {anyScope: true});
			}
		},
		// 'tasks.setPrivate'(taskId, setToPrivate) {
		//     check(taskId, String);
		//     check(setToPrivate, Boolean);
		//
		//     const task = Tasks.findOne(taskId);
		//
		//     // Make sure only the task owner can make a task private
		//     if (task.owner !== this.userId) {
		//         throw new Meteor.Error('not-authorized');
		//     }
		//
		//     Tasks.update(taskId, { $set: { private: setToPrivate } });
		// },
	});
}

// console.log("Users setup.")