// RemoveEntityFromAcl : Callback from EntityManager, when an entity is removed in order to remove
// the entity's permissions. This is needed to avoid giving a future
// new (unrelated) entity with the same name the permissions that
// were given to the original entity that was removed
func RemoveEntityFromAcl(el1 interface{}, userName string) {
	if el1 == nil {
		return
	}
	el, ok := el1.(*en.EntityManager)
	if ok == false {
		return
	}
	err := en.IsEntityNameValid(userName)
	if err != nil {
		return
	}
	for resourceName := range el.Resources {
		data, err := el.GetPropertyAttachedToEntity(resourceName, defs.AclPropertyName)
		if err != nil {
			continue
		}
		acl, ok := data.(*Acl)
		if ok == false {
			return
		}
		for name := range acl.Permissions {
			if name == userName {
				acl.removeAclEntry(userName)
			}
		}
	}
	return
}
// AddPermissionToEntity : Add the given permission to the given resource for the given entity
func (a *Acl) AddPermissionToEntity(el *en.EntityManager, entityName string, permission en.Permission) error {
	lock.Lock()
	defer lock.Unlock()

	if el == nil {
		return fmt.Errorf("entityManager is nil")
	}
	err := en.IsEntityNameValid(entityName)
	if err != nil {
		return err
	}
	if el.IsEntityInList(entityName) == false {
		return fmt.Errorf("Cannot add permission to entity '%v': It is not in the entity list", entityName)
	}
	if el.IsPermissionInList(permission) == false {
		return fmt.Errorf("Cannot add permission '%v' to entity '%v': It is not in the permissions list, please add it first", permission, entityName)
	}
	e, exist := a.Permissions[entityName]
	if exist == false {
		e, _ = NewEntry(entityName)
	}
	logger.Trace.Println("Add permission:", permission, "to:", entityName)
	_, err = e.AddPermission(permission)
	a.Permissions[entityName] = e
	return err
}
// CheckUserPermission : Check if the given user name has a given permission to the given entity
func CheckUserPermission(el *en.EntityManager, userName string, resourceName string, permission en.Permission) bool {
	if el == nil {
		return false
	}
	if en.IsEntityNameValid(userName) != nil {
		return false
	}
	if en.IsEntityNameValid(resourceName) != nil {
		return false
	}
	permissions, _ := GetUserPermissions(el, userName, resourceName)
	lock.Lock()
	defer lock.Unlock()
	_, exist := permissions[permission]
	logger.Trace.Println("Is permission:", permission, "of:", userName, "for entity:", resourceName, "set:", exist)
	return exist
}
// NewEntry : Generate a new ACL entry structure
func NewEntry(name string) (*Entry, error) {
	err := en.IsEntityNameValid(name)
	if err != nil {
		return nil, err
	}
	a := Entry{EntityName: name, Permissions: make(PermissionsMap)}
	return &a, nil
}
// GetUserPermissions : Get all the permissions of a given user to a given resource-
// return the user's list of permissions to the given resource
// The permissions may be listed as the user's permissions, permissions to groups
// in which the user is a member or permissions that are given to 'all'
func GetUserPermissions(el *en.EntityManager, userName string, resourceName string) (PermissionsMap, error) {
	lock.Lock()
	defer lock.Unlock()

	if el == nil {
		return nil, fmt.Errorf("entityManager is nil")
	}
	err := en.IsEntityNameValid(userName)
	if err != nil {
		return nil, err
	}
	err = en.IsEntityNameValid(resourceName)
	if err != nil {
		return nil, err
	}
	if el.IsEntityInList(userName) == false {
		return nil, fmt.Errorf("Entity %q is not in the entity manager", userName)
	}
	permissions := make(PermissionsMap)
	data, err := el.GetPropertyAttachedToEntity(resourceName, defs.AclPropertyName)
	if err != nil {
		return nil, fmt.Errorf("Resource '%v' does not have an ACL property", resourceName)
	}
	acl, ok := data.(*Acl)
	if ok == false {
		return nil, fmt.Errorf("Resource '%v' ACL property is in the wrong type", resourceName)
	}
	for name, p := range acl.Permissions {
		if name == userName || name == defs.AclAllEntryName || el.IsUserPartOfAGroup(name, userName) {
			for permission := range p.Permissions {
				permissions[permission] = ""
			}
		}
	}
	logger.Trace.Println("The permissions of:", userName, "are:", permissions)
	return permissions, nil
}
// Remove the given Entry from the ACL
func (a *Acl) removeAclEntry(name string) error {
	lock.Lock()
	defer lock.Unlock()

	err := en.IsEntityNameValid(name)
	if err != nil {
		return err
	}
	_, exist := a.Permissions[name]
	if exist == false {
		return fmt.Errorf("Cannot remove ACL entry '%v', it does not exist in the ACL", name)
	}
	logger.Trace.Println("Remove Entry:", name, "from acl")
	delete(a.Permissions, name)
	return nil
}
// GetWhoUseAPermission : Return all the users that have the given permission to the given resource
func GetWhoUseAPermission(el *en.EntityManager, resourceName string, permission string) PermissionSet {
	if el == nil {
		return nil
	}
	err := en.IsEntityNameValid(resourceName)
	if err != nil {
		return nil
	}
	data, err := el.GetPropertyAttachedToEntity(resourceName, defs.AclPropertyName)
	if err != nil {
		return nil
	}
	p := make(PermissionSet)

	acl, ok := data.(*Acl)
	if ok == false {
		return p
	}
	for name := range acl.Permissions {
		pVec, _ := GetUserPermissions(el, name, resourceName)
		for v := range pVec {
			if string(v) == permission {
				p[name] = ""
				break
			}
		}
	}
	for name := range p {
		groupMembers := el.GetGroupUsers(name)
		for _, name1 := range groupMembers {
			p[name1] = true
		}
	}
	logger.Trace.Println("Who uses permission:", permission, "results:", p)
	return p
}
// Verify that an Entry is valid, that is it's not nil and its Entry name is valid
func isValidAclEntry(aclEntry *Entry) error {
	if aclEntry == nil {
		return fmt.Errorf("aclEntry is nil")
	}
	return en.IsEntityNameValid(aclEntry.EntityName)
}