package com.yonge.cooleshow.auth.config;

import java.util.Collection;

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

import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.auth.service.SysUserService;
import com.yonge.cooleshow.common.security.AuthUser;
import com.yonge.cooleshow.common.security.SecurityUtils;

@Component("pcs")
public class PermissionCheckService {

	@Autowired
	private SysUserService sysUserService;

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

		AuthUser authUser = SecurityUtils.getUser();
		SysUser user = sysUserService.get(authUser.getUserId());
		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);
	}

}
