package info.bukova.isspst.ui;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

public class SecurityHelper {
	
	public static boolean isAllGranted(String authorities) {
        if (null == authorities || "".equals(authorities)) {
            return false;
        }
        final Collection<String> granted = getPrincipalAuthorities();
        boolean isAllGranted = granted.containsAll(parseAuthorities(authorities));
        return isAllGranted;
    }
 
    private static Collection<String> parseAuthorities(String authorities) {
		String[] auth = authorities.split(",");
		return Arrays.asList(auth);
	}

	private static Collection<String> getPrincipalAuthorities() {
        Authentication currentUser = SecurityContextHolder.getContext().getAuthentication();
        if (null == currentUser) {
            return Collections.emptyList();
        }
        if ((null == currentUser.getAuthorities()) || (currentUser.getAuthorities().isEmpty())) {
            return Collections.emptyList();
        }
        
        Collection<String> granted = new ArrayList<String>();
        for (GrantedAuthority a : currentUser.getAuthorities()) {
        	granted.add(a.getAuthority());
        }
        
        return granted;
    }

}
