"use strict";

var Promise = require('bluebird'),
    mongodb = Promise.promisifyAll(require('mongodb')),
	redis = Promise.promisifyAll(require('redis')),
	config = require('../config');
	
function openMongoConnection(db) {
	return mongodb.connectAsync(db.connectionString, db.options)
		.disposer(function(connection) {
			connection.close();
		});
}

function openRedisConnection(db) {
	return redis.createClient(db.port, db.host, db.options)
		.disposer(function(connection) {
			connection.quit();
		});
}

exports.connectToMongoDatabase = function(dbType) {
	return openMongoConnection(config.db.mongo[dbType]);
};

exports.connectToPlayerDatabase = function() {
	return exports.connectToMongoDatabase('player');
};

exports.connectToGameLibraryDatabase = function() {
	return exports.connectToMongoDatabase('gameLibrary');	
};

exports.connectToGameHistoryDatabase = function() {
	return exports.connectToMongoDatabase('gameHistory');
};

exports.connectToRedisDatabase = function(dbType) {
	return openRedisConnection(config.db.redis[dbType]);
};

exports.connectToSessionDatabase = function() {
	return exports.connectToRedisDatabase('session');
};

@@ -47,12 +47,9 @@
 '),%0A
-    
+%09
 mong
@@ -96,16 +96,77 @@
 odb')),%0A
+    MongoClient = Promise.promisifyAll(mongodb.MongoClient),%0A
 %09redis =
@@ -244,58 +244,409 @@
 ;%0A%09%0A
-function openMongoConnection(db) %7B%0A%09return mongodb
+%0Avar _mongoConnections = %7B %7D;%0A%0Afunction openMongoConnection(schemaName, db) %7B%0A%09var connectionReference = _mongoConnections%5BschemaName%5D;%0A%09if (connectionReference && connectionReference.referenceCount %3E 0) %7B%0A%09%09connectionReference.referenceCount = connectionReference.referenceCount + 1;%0A%09%7D else %7B%0A%09%09connectionReference = _mongoConnections%5BschemaName%5D = %7B%0A%09%09%09referenceCount: 1,%0A%09%09%09connection: MongoClient
 .con
@@ -680,32 +680,34 @@
 ng, db.options)%0A
+%09%09
 %09%09.disposer(func
@@ -732,32 +732,257 @@
 %0A%09%09%09
-connection.close();%0A%09%09%7D)
+%09%09_mongoConnections%5BschemaName%5D.referenceCount = _mongoConnections%5BschemaName%5D.referenceCount - 1;%0A%09%09%09%09%09if (0 === _mongoConnections%5BschemaName%5D.referenceCount) %7B%0A%09%09%09%09%09%09connection.close();%09%0A%09%09%09%09%09%7D%0A%09%09%09%09%7D)%0A%09%09%7D;%0A%09%7D%0A%09return connectionReference.connection
 ;%0A%7D%0A
@@ -1174,37 +1174,41 @@
 base = function(
-dbTyp
+schemaNam
 e) %7B%0A%09return ope
@@ -1216,32 +1216,44 @@
 MongoConnection(
+schemaName, 
 config.db.mongo%5B
@@ -1252,21 +1252,25 @@
 b.mongo%5B
-dbTyp
+schemaNam
 e%5D);%0A%7D;%0A

switch to MongoClient and ref count our connections