'use strict';

const mongodb = require('mongodb');
const config = require('./config');
const MongoClient = mongodb.MongoClient;
const dbpath = config.mongo;

let db = {};
let agentDb = {};
let newDb = {};

async function getDb() {
   const conn = await MongoClient.connect(dbpath);
   db = conn.db("remarketing");
   return db;
}

async function getAgentDb() {
   const conn = await MongoClient.connect(dbpath);
   agentDb = conn.db("remarketingAgent");
   return agentDb;
}

async function getNewDb() {
   const conn = await MongoClient.connect('mongodb://wjh:c9yJ2gBFkp7U6@10.11.3.136:1304/remarketingv3');
   newDb = conn.db("remarketingv3");
   return newDb;
}


async function getCollection (collectionName)
{
    if(!db.collection) {
        const db = await getDb();
        return db.collection(collectionName);
    }
    else return db.collection(collectionName);
}


async function getAgentCollection (collectionName)
{
    if(!agentDb.collection) {
        const agentDb = await getAgentDb();
        return agentDb.collection(collectionName);
    }
    else return agentDb.collection(collectionName);
}


async function getNewCollection (collectionName)
{
    if(!newDb.collection) {
        const newDb = await getNewDb();
        return newDb.collection(collectionName);
    }
    else return newDb.collection(collectionName);
}

module.exports =  {
    getCollection: getCollection,
    getNewCollection: getNewCollection,
    getAgentCollection: getAgentCollection,
    ObjectID: mongodb.ObjectID
};
