package ingraph.driver.neo4j;

import ingraph.driver.CypherDriver;
import org.neo4j.driver.v1.AccessMode;
import org.neo4j.driver.v1.AuthToken;
import org.neo4j.driver.v1.Driver;
import org.neo4j.driver.v1.GraphDatabase;
import org.neo4j.driver.v1.Session;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.factory.GraphDatabaseSettings;
import org.neo4j.test.TestGraphDatabaseFactory;

public class Neo4jDriver extends CypherDriver {

	final Driver driver;

	public Neo4jDriver(final String uri, final AuthToken authToken) {
		GraphDatabaseSettings.BoltConnector bolt = GraphDatabaseSettings.boltConnector("0");

		String host = "localhost";
		int port = 7687; // this is the default Neo4j port - we start one higher than this to avoid collisions
		GraphDatabaseService graphDb = null;
		String address = null;
		while (port < 65000) {
			port++;
			address = String.format("%s:%d", host, port);
			System.out.println("instantiating database listening on " + address);
			try {
				graphDb = new TestGraphDatabaseFactory()
					.newImpermanentDatabaseBuilder()
					.setConfig(bolt.type, "BOLT")
					.setConfig(bolt.enabled, "true")
					.setConfig(bolt.address, address)
					.newGraphDatabase();
			} catch (RuntimeException e) {
				// this is usually a org.neo4j.kernel.lifecycle.LifecycleException
				// caused by org.neo4j.helpers.PortBindException
				e.printStackTrace();
				System.out.println("Cannot connect on port " + port + ", retrying on a higher port.");
				continue;
			}
			break;
		}
		System.out.println(graphDb);

		driver = GraphDatabase.driver("bolt://" + address);
	}

	@Override
	public boolean isEncrypted() {
		return driver.isEncrypted();
	}

	@Override
	public Session session() {
		return driver.session();
	}

	@Override
	public Session session(final AccessMode mode) {
		return driver.session(mode);
	}

	@Override
	public Session session(final String bookmark) {
		throw new UnsupportedOperationException("unimplemented");
	}

	@Override
	public Session session(final AccessMode mode, final String bookmark) {
		throw new UnsupportedOperationException("unimplemented");
	}

	@Override
	public Session session(Iterable<String> bookmarks) {
		throw new UnsupportedOperationException("unimplemented");
	}

	@Override
	public Session session(AccessMode mode, Iterable<String> bookmarks) {
		return null;
	}

	@Override
	public void close() {
		driver.close();
	}

}

@@ -472,16 +472,53 @@
  driver;
+%0A%09final GraphDatabaseService graphDb;
 %0A%0A%09publi
@@ -826,24 +826,28 @@
 vice graphDb
+Temp
  = null;%0A%09%09S
@@ -1046,16 +1046,20 @@
 %09graphDb
+Temp
  = new T
@@ -1534,16 +1534,75 @@
 ort.%22);%0A
+%09%09%09%09if (graphDbTemp != null)%0A%09%09%09%09%09graphDbTemp.shutdown();%0A%0A
 %09%09%09%09cont
@@ -1654,17 +1654,46 @@
 (graphDb
-)
+Temp);%0A%09%09graphDb = graphDbTemp
 ;%0A%0A%09%09dri
@@ -2537,18 +2537,40 @@
 er.close();%0A
+%09%09graphDb.shutdown();%0A
 %09%7D%0A%0A%7D%0A

Add shutdown to Neo4jDriver