package org.neo4j.tutor.tree;

import java.util.Stack;

import org.neo4j.api.core.EmbeddedNeo;
import org.neo4j.api.core.Transaction;

// creates a file structure then prints it to console
public class ListFileStructure
{
	public static void main( String[] args )
	{
		EmbeddedNeo neo = new EmbeddedNeo( MyRelationshipTypes.class, 
			"var/file", true );
		// Ugly dependency injection
		FileFactory.getFactory().injectNeo( neo );
		// setup a file structure
		File root = setupFileStructure();
		// list files
		Stack<String> stack = new Stack<String>();
		stack.push( "/" );
		Transaction tx = Transaction.begin();
		for ( File child : root.getChildren() )
		{
			listFilesRecursive( child, stack );
		}
		tx.success();
		tx.finish();
		// cleanup
		tx = Transaction.begin();
		root.delete();
		tx.success();
		tx.finish();
		neo.shutdown();
	}

	private static void listFilesRecursive( File file, Stack<String> stack )
	{
		String fileName = stack.peek() + file.getFileName();
		System.out.println( fileName );
		stack.push( fileName + "/" );
		for ( File child : file.getChildren() )
		{
			listFilesRecursive( child, stack );
		}
		stack.pop();
	}

	private static File setupFileStructure()
	{
		Transaction tx = Transaction.begin();
		FileFactory factory = FileFactory.getFactory();
		File root = factory.createNewFile( "root" );
		root.addChild( factory.createNewFile( "bin" ) );
		root.addChild( factory.createNewFile( "boot" ) );
		root.addChild( factory.createNewFile( "dev" ) );
		File etc = factory.createNewFile( "etc" );
		etc.addChild( factory.createNewFile( "passwd" ) );
		etc.addChild( factory.createNewFile( "group" ) );
		root.addChild( etc );
		File home = factory.createNewFile( "home" );
		File neo = factory.createNewFile( "neo" );
		home.addChild( neo );
		neo.addChild( factory.createNewFile( "application.jar" ) );
		neo.addChild( factory.createNewFile( "readme.txt" ) );
		root.addChild( home );
		root.addChild( factory.createNewFile( "lib" ) );
		root.addChild( factory.createNewFile( "usr" ) );
		File sbin = factory.createNewFile( "sbin" );
		sbin.addChild( factory.createNewFile( "reboot" ) );
		sbin.addChild( factory.createNewFile( "fsck" ) );
		root.addChild( sbin );
		tx.success();
		tx.finish();
		return root;
	}
}
