package info.bukova.isspst.security;

import info.bukova.isspst.Constants;
import info.bukova.isspst.data.Permission;
import info.bukova.isspst.data.PermissionType;

import java.io.Serializable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;

public class IsPermissionEvaluator implements PermissionEvaluator {
	
	@Autowired
	private EvaluatorsHolder evalHolder;
	
	private static final Logger logger = LoggerFactory.getLogger(IsPermissionEvaluator.class);

	@Override
	public boolean hasPermission(Authentication authentication,
			Object targetDomainObject, Object permission) {
		
		Permission appPermission = null;
		for (Permission p : Constants.SPECIAL_PERMISSIONS) {
			if (p.getAuthority().equals(permission)) {
				appPermission = p;
			}
		}

		if (((String)permission).isEmpty()) {
			return false;
		}
		
		Evaluator eval = evalHolder.getForObject(targetDomainObject, appPermission != null && appPermission.getType() != PermissionType.GLOBAL);
		
		if (eval != null) {
			return eval.evaluate(authentication, targetDomainObject, (String)permission);
		}
		
		logger.warn("Evaluator for " + targetDomainObject.getClass().getName() + "not registred.");
		
		return false;
	}

	@Override
	public boolean hasPermission(Authentication authentication,
			Serializable targetId, String targetType, Object permission) {
		return false;
	}

}
