package org.neo4j.tutor.security;

import org.neo4j.api.core.Direction;
import org.neo4j.api.core.Node;
import org.neo4j.api.core.ReturnableEvaluator;
import org.neo4j.api.core.StopEvaluator;
import org.neo4j.api.core.TraversalPosition;
import org.neo4j.api.core.Traverser.Order;
import org.neo4j.impl.event.Event;
import org.neo4j.impl.event.EventData;

public class SecurityMgr2 extends AbstractSecurityMgr
{
	public boolean proActiveEventReceived( Event event, EventData data )
	{
		if ( event == SecurityEvent.ACCESS )
		{
			Node file = (Node) data.getData();
			final Node user = AuthorizationService.getCurrentUser();
			// --- TODO
			// --- Access granted by ACCESS relationship to a user
			// --- If no outgoing ACCESS relationship exist access is granted
			// --- else If no user registered (null user), access is denied
			// --- else traverse outgoing ACCESS relationships and if the user  
			// --- node is found return true
			if ( !file.getRelationships( 
				MyRelationshipTypes.ACCESS ).iterator().hasNext() )
			{
				return true;
			}
			if ( user == null )
			{
				return false;
			}
			return file.traverse( Order.DEPTH_FIRST, 
				StopEvaluator.DEPTH_ONE, new ReturnableEvaluator()
				{
					public boolean isReturnableNode( 
						TraversalPosition currentPosition )
					{
						return currentPosition.currentNode().equals( user );
					}
				}, 
				MyRelationshipTypes.ACCESS, 
				Direction.OUTGOING ).iterator().hasNext();
		}
		// we shouldn't get any other events but returning true by default 
		return true;
	}
}
