package info.bukova.isspst.security;

import info.bukova.isspst.Constants;
import info.bukova.isspst.data.FilterableRequirement;
import info.bukova.isspst.data.Permission;
import info.bukova.isspst.data.PermissionType;
import info.bukova.isspst.data.Role;
import info.bukova.isspst.data.User;
import info.bukova.isspst.data.Workgroup;
import info.bukova.isspst.services.workgroups.WorkgroupService;

import java.util.List;

import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.core.Authentication;

/**
 * Filtr kolekce objektů {@link FilterableRequirement}. Podle role, kterou má uživatel
 * na středisku/komisi ve které je požadavek, se vyhodnotí, zda má uživatel právo ho
 * zobrazit. Požití s anotací {@link PostFilter}.
 * 
 * @author pepa
 *
 */
public class RequirementFilterEvaluator implements Evaluator {
	
	private WorkgroupService wgService;
	
	public RequirementFilterEvaluator(WorkgroupService wgService) {
		this.wgService = wgService;
	}

	/**
	 * 
	 * @see info.bukova.isspst.security.Evaluator#evaluate(org.springframework.security.core.Authentication, java.lang.Object, java.lang.String)
	 * @param authentication		objekt přihlášeného uživatele
	 * @param targetDomainObject	objekt požadavku
	 * @param permission			oprávnění nutné k zobrazení
	 * 
	 */
	@Override
	public boolean evaluate(Authentication authentication,
			Object targetDomainObject, String permission) {
		
		FilterableRequirement req = (FilterableRequirement) targetDomainObject;
		Workgroup reqWg;
		
		if (!(authentication.getPrincipal() instanceof User)) {
			return false;
		}
		
		User user = (User)authentication.getPrincipal();
		
		Permission appPermission = null;
		for (Permission p : Constants.SPECIAL_PERMISSIONS) {
			if (p.getAuthority().equals(permission)) {
				appPermission = p;
			}
		}
		
		if (appPermission == null) {
			return false;
		}
		
		if (appPermission.getType() == PermissionType.CENTRE) {
			reqWg = req.getCentre();
		} else {
			reqWg = req.getWorkgroup();
		}
		
		if (wgService.isMember(reqWg, user)) {
			List<Role> roles = wgService.getUserWorkgroupRoles(reqWg, user);
			for (Role r : roles) {
				for (Permission p : r.getPermissions()) {
					if (p.getAuthority().equals(appPermission.getAuthority())) {
						return true;
					}
				}
			}
		}
		
		return false;
	}

}
