package com.conveyal.taui.persistence;

import com.conveyal.taui.AnalystConfig;
import com.conveyal.taui.models.Bundle;
import com.conveyal.taui.models.Model;
import com.conveyal.taui.models.Modification;
import com.conveyal.taui.models.Scenario;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.mongojack.JacksonDBCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;
import java.util.Map;

/**
 * Manages a single connection to MongoDB for the entire TAUI server process.
 */
public class Persistence {
    private static final Logger LOG = LoggerFactory.getLogger(Persistence.class);

    // TODO deprecated but needed for MongoJack
    private static Mongo mongo;
    private static DB db;

    public static Map<String, Modification> modifications;
    public static Map<String, Scenario> scenarios;
    public static Map<String, Bundle> bundles;

    public static void initialize () {
        LOG.info("Connecting to MongoDB");
        // allow configurable db connection params

        String mongoUrl = System.getenv("MONGO_URL");
        // this is the name of the environment variable created by heroku
        if (mongoUrl == null) mongoUrl = System.getenv("MONGOLAB_URI");

        if (mongoUrl != null) {
            mongo = new Mongo(mongoUrl);
            LOG.info("Connecting to remote MongoDB instance");
        }
        else {
            LOG.info("Connecting to local MongoDB instance");
            mongo = new Mongo();
        }

        db = mongo.getDB(AnalystConfig.databaseName);

        modifications = getTable("modifications", Modification.class);
        scenarios = getTable("scenarios", Scenario.class);
        bundles = getTable("bundles", Bundle.class);
    }

    /** connect to a table using MongoJack */
    private static <V extends Model> Map<String, V> getTable (String name, Class clazz) {
        DBCollection collection = db.getCollection(name);
        JacksonDBCollection<V, String> coll = JacksonDBCollection.wrap(collection, clazz, String.class);
        return new MongoMap<>(coll);
    }
}

@@ -354,16 +354,45 @@
 Client;%0A
+import com.mongodb.MongoURI;%0A
 import c
@@ -1226,209 +1226,59 @@
     
-String mongoUrl = System.getenv(%22MONGO_URL%22);%0A        // this is the name of the environment variable created by heroku%0A        if (mongoUrl == null) mongoUrl = System.getenv(%22MONGOLAB_URI%22);%0A%0A
+if (AnalystConfig.databaseUri != null) %7B%0A  
         
 if (
@@ -1277,52 +1277,28 @@
     
-if (
+  
 mongo
-Url != null) %7B%0A            m
+ = new M
 ongo
- = 
+(
 new 
@@ -1306,17 +1306,38 @@
 ongo
-(mongoUrl
+URI(AnalystConfig.databaseUri)
 );%0A 

fix mongo uri parsing code.