import {Random} from 'meteor/random';

if(Meteor.isServer) {
	Meteor.publish('users', function() {
		if(Roles.userIsInRole(this.userId, ['manage'])) {
			return Meteor.users.find({}, {fields: {username: 1, emails: 1, roles: 1}});
		}
		else throw new Meteor.Error(403, "Not authorized to view users.");
	});
	
	Meteor.methods({
		"insertUser": function(user) {
			check(user, {
				username: String,
				email: String,
				roles: [String]
			});
			
			//Verify the currently logged in user has authority to manage users.
			if(Roles.userIsInRole(this.userId, [Meteor.UserRoles.ROLE_MANAGE])) {
				//Verify the user name isn't already used.
				if(Meteor.collections.Users.findOne({username: user.username}) === undefined) {
					let pwd = Random.secret(20);
					let id = Accounts.createUser({password: pwd, username: user.username, email: user.email});
					
					//Requires the alanning:roles package.
					Roles.addUsersToRoles(id, user.roles);
				}
				else {
					throw new Meteor.Error(400, "User already exists.");
				}
			}
			else throw new Meteor.Error(403, "Not authorized to add users.");
		},
		"updateUser": function(user) {
			check(user, {
				_id: String,
				username: String,
				emails: [{
					address: String,
					verified: Boolean
				}],
				roles: [String]
			});
			
			//Verify the currently logged in user has authority to manage users.
			if(Roles.userIsInRole(this.userId, [Meteor.UserRoles.ROLE_MANAGE])) {
				//Verify the user name isn't already used with a different ID.
				if(Meteor.collections.Users.findOne({username: user.username, _id: {$ne: user._id}}) == undefined) {
					//Update the user.  Note: I am using direct mongo modification, versus attempting to go through the Accounts and Roles objects.  This could cause problems in the future if these packages change their data structures.
					Meteor.collections.Users.update(user._id, {$set: {username: user.username, emails: user.emails, roles: user.roles}});
				}
				else {
					throw new Meteor.Error(400, "User name already exists.");
				}
			}
			else throw new Meteor.Error(403, "Not authorized to update users.");
		},
		"deleteUser": function(id) {
			check(id, String);
			if(Roles.userIsInRole(this.userId, [Meteor.UserRoles.ROLE_MANAGE])) {
				Meteor.collections.Users.remove(id);
			}
			else throw new Meteor.Error(403, "Not authorized to remove users.");
		}
	});
}

export default Meteor.users;