package unit.security;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

import org.neo4j.api.core.EmbeddedNeo;
import org.neo4j.api.core.Node;
import org.neo4j.impl.event.EventData;
import org.neo4j.impl.event.EventManager;
import org.neo4j.api.core.Transaction;
import org.neo4j.tutor.security.File;
import org.neo4j.tutor.security.FileFactory;
import org.neo4j.tutor.security.MyRelationshipTypes;
import org.neo4j.tutor.security.SecurityEvent;
import org.neo4j.tutor.security.SecurityMgr1;

public class TestSecurity1 extends TestCase
{
	public TestSecurity1( String testName )
	{
		super( testName );
	}
	
	public static Test suite()
	{
		TestSuite suite = new TestSuite( TestSecurity1.class );
		return suite;
	}
	
	private SecurityMgr1 securityManager = new SecurityMgr1();
	private EmbeddedNeo neo;
	private Transaction tx;
	
	public void setUp()
	{
		neo = new EmbeddedNeo( MyRelationshipTypes.class, "var/security-test", 
			true );
		securityManager.registerEventListener();
		FileFactory.getFactory().injectNeo( neo );
		tx = Transaction.begin();
	}
	
	public void tearDown()
	{
		tx.finish();
		securityManager.unregisterEventListner();
		neo.shutdown();
	}
	
	public void testSimpleSecurityMgr1()
	{
		Node fileNode = neo.createNode();
		fileNode.setProperty( File.NAME, "atestfile" );
		tx.success();
		tx.finish();
		tx = Transaction.begin();
		EventManager evtMgr = EventManager.getManager();
		EventData eventData = new EventData( fileNode ); 
		// no property should equal access
		assertTrue( evtMgr.generateProActiveEvent( 
			SecurityEvent.ACCESS, eventData ) );
		fileNode.setProperty( File.SECURITY, new Boolean( true ) );
		assertTrue( evtMgr.generateProActiveEvent( 
			SecurityEvent.ACCESS, eventData ) );
		fileNode.setProperty( File.SECURITY, new Boolean( false ) );
		assertTrue( !evtMgr.generateProActiveEvent( 
			SecurityEvent.ACCESS, eventData ) );
		fileNode.delete();
		tx.success();
	}
	
	public void testGetChildren()
	{
		FileFactory factory = FileFactory.getFactory();
		File root = factory.createNewFile( "root" );
		File file1 = factory.createNewFile( "fileAccessOk1" );
		File file2 = factory.createNewFile( "fileNoAccess1" );
		File file3 = factory.createNewFile( "fileAccessOk2" );
		File file4 = factory.createNewFile( "fileNoAccess2" );
		root.addChild( file1 );
		root.addChild( file2 );
		root.addChild( file3 );
		root.addChild( file4 );
		file2.getUnderlyingNode().setProperty( File.SECURITY, false );
		file4.getUnderlyingNode().setProperty( File.SECURITY, false );
		tx.success();
		tx.finish();
		tx = Transaction.begin();
		int count = 0;
		for ( File file : root.getChildren() )
		{
			assertTrue( file.equals( file1 ) || file.equals( file3 ) );
			count++;
		}
		assertEquals( 2, count );
		root.delete();
		tx.success();
	}
}
