/**
 * Copyright (c) 2002-2013 "Neo Technology,"
 * Network Engine for Objects in Lund AB [http://neotechnology.com]
 *
 * This file is part of Neo4j.
 *
 * Neo4j is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.neo4j.server.helpers;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.index.IndexManager;
import org.neo4j.server.NeoServer;
import org.neo4j.tooling.GlobalGraphOperations;

public class ServerHelper
{
    public static void cleanTheDatabase( final NeoServer server )
    {
        if ( server == null )
        {
            return;
        }

        new Transactor( server.getDatabase().getGraph(), new UnitOfWork()
        {

            @Override
            public void doWork()
            {
                deleteAllNodesAndRelationships( server );

                deleteAllIndexes( server );
            }

            private void deleteAllNodesAndRelationships( final NeoServer server )
            {
                Iterable<Node> allNodes = GlobalGraphOperations.at( server.getDatabase().getGraph() ).getAllNodes();
                for ( Node n : allNodes )
                {
                    Iterable<Relationship> relationships = n.getRelationships();
                    for ( Relationship rel : relationships )
                    {
                        rel.delete();
                    }
                    if ( n.getId() != 0 )
                    { // Don't delete the reference node - tests depend on it
                      // :-(
                        n.delete();
                    }
                    else
                    { // Remove all state from the reference node instead
                        for ( String key : n.getPropertyKeys() )
                        {
                            n.removeProperty( key );
                        }
                    }
                }
            }

            private void deleteAllIndexes( final NeoServer server )
            {
                IndexManager indexManager = server.getDatabase().getGraph().index();
                
                for ( String indexName : indexManager.nodeIndexNames() )
                {
                	try{
	                    server.getDatabase().getGraph().index()
	                            .forNodes( indexName )
	                            .delete();
                	} catch(UnsupportedOperationException e) {
                		// Encountered a read-only index.
                	}
                }

                for ( String indexName : indexManager.relationshipIndexNames() )
                {
                	try {
	                    server.getDatabase().getGraph().index()
	                            .forRelationships( indexName )
	                            .delete();
                	} catch(UnsupportedOperationException e) {
                		// Encountered a read-only index.
                	}
                }
                
                for(String k : indexManager.getNodeAutoIndexer().getAutoIndexedProperties()) 
                {
                    indexManager.getNodeAutoIndexer().stopAutoIndexingProperty(k);
                }
                indexManager.getNodeAutoIndexer().setEnabled(false);
                
                for(String k : indexManager.getRelationshipAutoIndexer().getAutoIndexedProperties()) 
                {
                    indexManager.getRelationshipAutoIndexer().stopAutoIndexingProperty(k);
                }
                indexManager.getRelationshipAutoIndexer().setEnabled(false);
            }
        } ).execute();

        removeLogs( server );
    }

    private static void removeLogs( NeoServer server )
    {
        File logDir = new File( server.getDatabase().getLocation() + File.separator + ".." + File.separator + "log" );
        try
        {
            FileUtils.deleteDirectory( logDir );
        }
        catch ( IOException e )
        {
            throw new RuntimeException( e );
        }
    }

    public static NeoServer createNonPersistentServer() throws IOException
    {
        return createServer( false, null );
    }

    public static NeoServer createPersistentServer(File path) throws IOException
    {
        return createServer( true, path );
    }

    private static NeoServer createServer( boolean persistent, File path ) throws IOException
    {
        ServerBuilder builder = ServerBuilder.server();
        configureHostname( builder );
        if ( persistent ) builder = builder.persistent();
        NeoServer server = builder
                .usingDatabaseDir( path != null ? path.getAbsolutePath() : null)
                .build();
        server.start();
        return server;
    }

    private static void configureHostname( ServerBuilder builder )
    {
        String hostName = System.getProperty( "neo-server.test.hostname" );
        if (StringUtils.isNotEmpty( hostName )) {
            builder.onHost( hostName );
        }
    }
}

@@ -873,16 +873,75 @@
 ception;
+%0Aimport java.net.InetAddress;%0Aimport java.net.ServerSocket;
 %0A%0Aimport
@@ -2855,32 +2855,16 @@
 ndex();%0A
-                
 %0A       
@@ -3704,32 +3704,16 @@
       %7D%0A
-                
 %0A       
@@ -3789,33 +3789,32 @@
 xedProperties())
- 
 %0A               
@@ -3986,32 +3986,16 @@
 false);%0A
-                
 %0A       
@@ -4087,17 +4087,16 @@
 rties())
- 
 %0A       
@@ -5399,54 +5399,624 @@
 ();%0A
-        server.start();%0A        return server;
+%0A        checkServerCanStart(server.baseUri().getHost(), server.baseUri().getPort());%0A%0A        server.start();%0A        return server;%0A    %7D%0A%0A    private static void checkServerCanStart(String host, int port) throws IOException %7B%0A        ServerSocket serverSocket = null;%0A        try %7B%0A            serverSocket = new ServerSocket(port, 1, InetAddress.getByName(host));%0A        %7D catch(IOException ex) %7B%0A            throw new RuntimeException(%22Unable to start server on %22 + host + %22:%22 + port, ex);%0A        %7D finally %7B%0A            if(serverSocket != null) %7B%0A                serverSocket.close();%0A            %7D%0A        %7D
 %0A   

Check if server can be started before starting it for server tests