package com.yonge.cooleshow.admin.config;

import java.util.Collection;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import com.yonge.cooleshow.auth.api.client.SysUserFeignService;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.common.security.SecurityUtils;

@Component("pcs")
public class PermissionCheckService {
	
	@Autowired
	@Lazy
	private SysUserFeignService sysUserFeignService;

	public boolean hasPermissions(String... permissions) {
		Authentication authentication = SecurityUtils.getAuthentication();
		if (authentication == null) {
			return false;
		}

		SysUser user = sysUserFeignService.queryUserInfo();
		if(user.getIsSuperAdmin()){
			return true;
		}

		Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

		for (String perm : permissions) {
			for (GrantedAuthority authority : authorities) {
				if (StringUtils.equalsIgnoreCase(perm, authority.getAuthority())) {
					return true;
				}
			}
		}

		return false;
	}

	public boolean hasRoles(String... roles) {

		return hasPermissions(roles);
	}

}
