package com.yonge.cooleshow.common.security;

import java.util.Collection;

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

//@Component("pcs")
public class PermissionCheckService {

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

		String username = authentication.getName();

		if (StringUtils.startsWith(username, SecurityConstants.USERNAME_PRINCIPAL_PREFIX)) {
			if ("admin".equals(StringUtils.removeStart(username, SecurityConstants.USERNAME_PRINCIPAL_PREFIX))) {
				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);
	}

}
