package info.bukova.isspst.security;

import info.bukova.isspst.Constants;
import info.bukova.isspst.Module;
import info.bukova.isspst.data.Role;

import java.util.List;

import org.springframework.security.core.Authentication;

public abstract class AbstractModuleEvaluator implements Evaluator {
	
	@SuppressWarnings("unchecked")
	protected boolean hasModulePermission(Authentication authentication, Class<?> serviceClass, String permission) {
		List<Role> roles = (List<Role>) authentication.getAuthorities();
		String moduleId = "";
		String perm = permission;
		
		for (Module m : Constants.MODULES) {
			if (m.getServiceClass() != null && m.getServiceClass().isAssignableFrom(serviceClass)) {
				moduleId = m.getId();
				break;
			}
		}
		
		perm += "_" + moduleId;
		
		for (int i = 0; i < roles.size(); i++) {
			if (!(roles.get(i) instanceof Role)) {
				return false;
			}
			if (roles.get(i).getAuthority().equals(perm)) {
				return true;
			}
			if (roles.get(i).getAuthority().equals(Constants.ROLE_ADMIN)) {
				return true;
			}
		}
		
		return false;
	}

}
