const log      = require('../utils/log.utils');          // Log Helper

const dbUser = process.env.OWL_DB_USER || "owl"
const dbPass = process.env.OWL_DB_PASS || "twittwoo"
const dbName = process.env.OWL_DB_NAME || "owlboard"
const dbPort = process.env.OWL_DB_PORT || 27017
const dbHost = process.env.OWL_DB_HOST || "localhost"
const uri = `mongodb://${dbUser}:${dbPass}@${dbHost}:${dbPort}`;

const { MongoClient } = require('mongodb');

const client = new MongoClient(uri);
const db = client.db(dbName);

async function dropCollection(coll){
    log.out(`DbAccess: Removing Existing ${coll} data`)
    await client.connect();

    try {
        db.dropCollection(coll);
        log.out(`DbAccess: Collection ${coll} dropped`)
    } catch (error) {
        log.out(`DbAccess: Error deleting collection ${coll}`)
        log.out(error)
    }
}

async function putCorpus(data){
    log.out("DbAccess: Uploading CORPUS data to database")
    await client.connect();
    var coll = db.collection("corpus");
    try {
        await coll.insertMany(data);
        log.out("DbAccess: Corpus upload complete")
    } catch (error) {
        log.out("DbAccess: Error uploading Corpus data to database")
        log.out(error)
    }
};

async function putStations(data){
    log.out("DbAccess: Uploading Stations data to database")
    await client.connect();
    var coll = db.collection("stations");
    try {
        coll.insertMany(data);
        log.out("DbAccess: Stations upload complete")
    } catch (error) {
        log.out("DbAccess: Error uploading Stations data to database")
        log.out(error)
    }
};

async function putMeta(data){
    await client.connect();
    var coll = db.collection("meta");
    coll.insertMany(data);
}

async function query(collection, query){
    await client.connect();
    let qcoll = db.collection(collection);
    let qcursor = qcoll.find(query)
    let qresult = await qcursor.toArray();
    return qresult;
}

module.exports = {
    putCorpus,
    putStations,
    dropCollection,
    putMeta,
    query
}