package org.ccpit.base.user;

import java.util.Set;

import org.ccpit.base.dao.BaseDao;
import org.ccpit.base.role.Role;
import org.ccpit.base.usergroup.UserGroupDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 * 用户实体操作类
 * Created by sqp on 2015/9/5.
 */
@Repository
public class UserDao extends BaseDao<User> {
    @Autowired
    private UserGroupDao userGroupDao;

    public User getUserByLoginName(String loginName){
    	String hql = "from User where loginName = ?";
    	User user = super.findUnique(hql, new String[]{loginName});
    	return user;
    }
    /**
     * 
     * getUserByLoginEmail:(根据邮箱账号查询). <br/>
     * @author dingwei
     * @param registerEamil
     * @return
     * @since JDK 1.6
     */
    public User getUserByLoginEmail(String registerEamil){
    	String hql = "from User where email = ?";
    	User user = super.findUnique(hql, new String[]{registerEamil});
    	return user;
    }
    
    /**
     * 检查用户是否具有此角色 或者用户所在的组是否具有此角色
     *
     * @param user
     * @param role
     * @return
     */
    public boolean canUserOrInGroup(User user, Role role){
        boolean can = canUser(user, role);
        if (!can){
            can = userGroupDao.canUserInGroup(user,role);
        }
        return can;
    }

    /**
     * 获取一个用户所拥有的所有角色，包括用户所在的组拥有的角色
     * @param user
     * @return
     */
    public Set<Role> getUserRolesIncludeGroup(User user){
        Set<Role> roles = user.getRoles();
        Set<Role> rolesInGroup = userGroupDao.getRolesForUser(user);
        roles.addAll(rolesInGroup);
        return roles;
    }

    /**
     * 判断用户是否具有某个角色
     * @param user
     * @param role
     * @return
     */
    public boolean canUser(User user,Role role){
        return user.getRoles().contains(role);
    }

}
