package org.neo4j.tutor.search;

import java.util.Collections;
import org.neo4j.api.core.Direction;
import org.neo4j.api.core.EmbeddedNeo;
import org.neo4j.api.core.Node;
import org.neo4j.api.core.Relationship;
import org.neo4j.api.core.ReturnableEvaluator;
import org.neo4j.api.core.StopEvaluator;
import org.neo4j.api.core.TraversalPosition;
import org.neo4j.api.core.Traverser;
import org.neo4j.api.core.Traverser.Order;

public class SearchEngine extends AbstractSearchEngine
{
	public SearchEngine( EmbeddedNeo neo )
	{
		super( neo );
	}
	
	public Iterable<Node> searchDocuments( String language, String keyword )
	{
		Node keywordNode = getKeywordNode( language, keyword );
		if ( keywordNode == null )
		{
			System.out.println( "Keyword not found" );
			return Collections.emptyList();
		}
		// --- TODO 
		// --- Find all documents that has keyword connected to it and 
		// --- all documents connected to other languages that keyword 
		// --- translates to
		// --- Do this by creating a traverser from the keywordNode and traverse
		// --- the TRANSLATION and HAS_KEYWORD relationships.
		// return keywordNode.traverse( ... ).getAllNodes();
		Traverser traverser = keywordNode.traverse( Order.DEPTH_FIRST, 
			StopEvaluator.END_OF_NETWORK, 
			new ReturnableEvaluator()
			{
				public boolean isReturnableNode( 
					TraversalPosition currentPosition )
				{
					Relationship last = 
						currentPosition.lastRelationshipTraversed();
					if ( last != null && last.getType().equals(  
						MyRelationshipTypes.HAS_KEYWORD ) )
					{
						return true;
					}
					return false;
				}
			}, MyRelationshipTypes.HAS_KEYWORD, Direction.INCOMING, 
			MyRelationshipTypes.TRANSLATION, Direction.BOTH );
		return traverser.getAllNodes();
		//return null;
	}
}
