package com.goafanti.core.shiro.token;

import java.util.Set;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.druid.support.logging.Log;
import com.goafanti.admin.service.AdminService;
import com.goafanti.common.model.Admin;
import com.goafanti.common.model.AftUser;
import com.goafanti.common.model.User;
import com.goafanti.common.utils.PasswordUtil;
import com.goafanti.permission.service.PermissionService;
import com.goafanti.permission.service.RoleService;
import com.goafanti.user.service.UserService;

public class UserRealm extends AuthorizingRealm {
	@Autowired
	UserService				userService;
	@Autowired
	AdminService			adminService;
	@Autowired
	RoleService				roleService;
	@Autowired
	PermissionService		permissionService;

	@Resource(name = "passwordUtil")
	private PasswordUtil	passwordUtil;

	public UserRealm() {
		super();
	}

	/**
	 * 登录
	 */
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
			throws AuthenticationException {

		ShiroToken token = (ShiroToken) authcToken;
		if (null == token.getType()) {
			Admin admin = adminService.selectByMobile(token.getUsername());
			if (null == admin) {
				throw new UnknownAccountException();
			}
			token.setId(admin.getId());
			AftUser aftUser = admin;
			return new SimpleAuthenticationInfo(aftUser, aftUser.getPassword(), passwordUtil.getAftSalt(aftUser),
					getName());
		} else {
			User user = userService.selectByMobieAndType(token.getUsername(), token.getType());
			if (null == user) {
				throw new UnknownAccountException();
			}
			token.setId(user.getId());
			AftUser aftUser = user;
			return new SimpleAuthenticationInfo(aftUser, aftUser.getPassword(), passwordUtil.getAftSalt(aftUser),
					getName());
		}
	}

	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String userId = TokenManager.getAdminId();
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
			System.out.println("=============================获取权限");
		// 根据用户ID查询角色（role），放入到Authorization里。
		Set<String> roles = roleService.findRoleByUserId(userId);
		System.out.println("============================role:" +roles.toString());
		info.setRoles(roles);
		// 根据用户ID查询权限（permission），放入到Authorization里。
		Set<String> permissions = permissionService.findPermissionByUserId(userId);
		System.out.println("============================permissions:" +permissions.toString());
		info.setStringPermissions(permissions);
		return info;
	}

	/**
	 * 清空当前用户权限信息
	 */
	public void clearCachedAuthorizationInfo() {
		AftUser principal = (AftUser) SecurityUtils.getSubject().getPrincipal();
		SimplePrincipalCollection principals = new SimplePrincipalCollection(principal.getId(), getName());
		super.clearCachedAuthorizationInfo(principals);
	}

	/**
	 * 指定principalCollection 清除
	 */
	public void clearCachedAuthorizationInfo(String... userIds) {
		if (null == userIds || userIds.length == 0)
			return;
		for (String uid : userIds) {
			super.clearCachedAuthorizationInfo(new SimplePrincipalCollection(uid, getName()));
		}
	}

	@Override
	protected Object getAuthorizationCacheKey(PrincipalCollection principals) {
		Object principal = principals.getPrimaryPrincipal();
		if (principal instanceof AftUser) {
			return ((AftUser) principal).getId();
		}
		return principal;
	}
}
