 @Groups = new Mongo.Collection 'groups'
 
 @findGroup = (group) ->
+  return group if group.name?
   Groups.findOne
     name: group
 

    @autorun ->
      readableGroups @userId

  @groupMembers = (group, options) ->
    ## Mimic memberOfGroup above
    Meteor.users.find
      "roles.#{escapeGroup group}":
        $exists: true
        $ne: []
    , options

  Meteor.publish 'groups.members', (group) ->
    check group, String
    if groupRoleCheck group, 'read', findUser @userId
      id = findGroup(group)._id
      @autorun ->
        groupMembers group,
          fields:
            username: 1
            profile: 1
      init = true
      @autorun ->
        members =
          members: groupMembers(group, fields: username: 1).map (user) -> user.username
        if init
          init = false
          members.group = group
          @added 'groups.members', id, members
        else
          @changed 'groups.members', id, members
    @ready()

if Meteor.isClient
  @GroupsMembers = new Mongo.Collection 'groups.members'

  @groupMembers = (group) ->
    GroupsMembers.findOne
      group: group
    ?.members ? []

  @sortedGroupMembers = (group) ->
    _.sortBy groupMembers(group), userSortKey

Meteor.methods
  setRole: (group, user, role, yesno) ->

@memberOfGroup = (group, user = Meteor.user()) ->
  roles = user?.roles?[escapeGroup group]
  roles and roles.length > 0

## List all groups that the user is a member of.
## (Mimicking memberOfGroup above.)
@memberOfGroups = (user = Meteor.user()) ->
  for group, roles of user?.roles ? {}
    continue unless roles.length > 0
    continue if group == wildGroup
    unescapeGroup group

if Meteor.isServer
  @readableGroups = (userId) ->
