package org.ccpit.base.usergroup;

import org.ccpit.base.dao.BaseDao;
import org.ccpit.base.role.Role;
import org.ccpit.base.user.User;
import org.springframework.stereotype.Repository;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 用户组数据操作表
 * Created by Administrator on 2015/9/7.
 */
@Repository
public class UserGroupDao extends BaseDao<UserGroup> {
    /**
     * 查询用户所在的用户组
     *
     * @param user
     * @return
     */
    public List<UserGroup> getUserGroupsByUser(User user) {
        return query("select distinct ug from " + UserGroup.class.getName() + " as ug left join ug.users as u " +
                "where u.id=? ", user.getId());
    }

    /**
     * 查询所有拥有此角色的用户组
     *
     * @param role
     * @return
     */
    public List<UserGroup> getUserGroupsByRole(Role role) {
        return query("select distinct ug from " + UserGroup.class.getName() + " as ug left join ug.roles as r " +
                "where r.id=? ", role.getId());
    }


    /**
     * 用户所在的组是否具有role的角色
     *
     * @param user
     * @param role
     * @return
     */
    public boolean canUserInGroup(User user, Role role) {
        List<UserGroup> userGroups = getUserGroupsByUser(user);
        Set<Role> roleSet = new HashSet<Role>();
        for (UserGroup userGroup : userGroups) {
            roleSet.addAll(userGroup.getRoles());
        }
        return roleSet.contains(role);
    }

    /**
     * 获取用户所在组的所有角色
     * @param user
     * @return
     */
    public Set<Role> getRolesForUser(User user){
        List<UserGroup> groups = getUserGroupsByUser(user);
        Set<Role> roles = new HashSet<Role>();
        for (UserGroup userGroup:groups){
            roles.addAll(userGroup.getRoles());
        }
        return roles;
    }

}
