package pw.scho.battleship.persistence.configuration;


import com.mongodb.ServerAddress;
import org.mongolink.MongoSession;
import org.mongolink.MongoSessionManager;
import org.mongolink.Settings;
import org.mongolink.UpdateStrategies;
import org.mongolink.domain.mapper.ContextBuilder;

import java.net.UnknownHostException;
import java.util.Arrays;

public class MongoConfiguration {

    public static void stop() {
        Singleton.INSTANCE.mongoSessionManager.close();
    }

    public static MongoSession createSession() {
        return Singleton.INSTANCE.mongoSessionManager.createSession();
    }

    private enum Singleton {

        INSTANCE;

        private final MongoSessionManager mongoSessionManager;

        private Singleton() {
            ContextBuilder builder = new ContextBuilder("pw.scho.battleship.persistence.mongo.mapping");
            Settings settings = null;
            try {
                settings = Settings.defaultInstance()
                        .withDefaultUpdateStrategy(UpdateStrategies.DIFF)
                        .withDbName("battleship")
                        .withAddresses(Arrays.asList(new ServerAddress("localhost", 27017)));

            } catch (UnknownHostException e) {
            }
            mongoSessionManager = MongoSessionManager.create(builder, settings);
        }
    }
}

@@ -49,16 +49,68 @@
 tion;%0A%0A%0A
+import com.mongodb.DB;%0Aimport com.mongodb.MongoURI;%0A
 import c
@@ -135,16 +135,16 @@
 ddress;%0A
-
 import o
@@ -334,16 +334,73 @@
 ilder;%0A%0A
+import java.net.URI;%0Aimport java.net.URISyntaxException;%0A
 import j
@@ -421,32 +421,60 @@
 nHostException;%0A
+import java.util.ArrayList;%0A
 import java.util
@@ -481,16 +481,39 @@
 .Arrays;
+%0Aimport java.util.List;
 %0A%0Apublic
@@ -1244,16 +1244,17 @@
 leship%22)
+;
 %0A       
@@ -1258,32 +1258,656 @@
             
-        
+String mongoHqUrl = System.getenv(%22MONGOHQ_URL%22);%0A%0A                if(mongoHqUrl!= null)%7B%0A                    MongoURI mongoURI = new MongoURI(mongoHqUrl);%0A                    List%3CServerAddress%3E serverAdresses = new ArrayList%3C%3E();%0A                    for(String host : mongoURI.getHosts())%7B%0A                        serverAdresses.add(new ServerAddress(host, 27017));%0A                    %7D%0A                    settings = settings.withAddresses(serverAdresses)%0A                            .withAuthentication(mongoURI.getUsername(), mongoURI.getPassword().toString());%0A                %7D else %7B%0A                    settings = settings
 .withAddress
@@ -1964,16 +1964,33 @@
 017)));%0A
+                %7D
 %0A       

Add mongo hq authentication for heroku