// FUNCTIONS
//  init()   : Exported: Uses the internal functions to initialise databases.
//  check()  : 
//  build()  : Adds CORPUS Data to DB.

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

async function init(){
    var status = check();
    // if check() returns false run build, else break.
}

async function check(){
    log.out("DbInit: Checking database state")
    let test = {'collection': 'any'};
    try {
        let meta = await dbAccess.query('meta',test);
        log.out(`DbInit: Reading Database Collection: meta`);
    } catch (error) {log.out(error)}  
    if (true){
        log.out("DbInit: Database structure not initialised")
        build("all")
    }
}

async function build(db){  // `db` must be one of: `corpus`, `stations`, `all`.
    log.out("DbInit: Building database structure")
    var corpusAll = await corpus.get();
    if (db === "corpus" || "all") {
        await dbAccess.dropCollection("corpus");
        dbAccess.putCorpus(corpusAll);
        meta = [{collection:"any",updated:Math.floor(Date.now() / 1000)}];
        dbAccess.putMeta(meta);
    }
    if (db === "stations" || "all") {
        await dbAccess.dropCollection("stations");
        var corpusSubset = await corpus.subset(corpusAll);
        dbAccess.putStations(corpusSubset);
        meta = [{collection:"any",updated:Math.floor(Date.now() / 1000)}];
        dbAccess.putMeta(meta);
    }
}

module.exports = {
    init,
    check,
    build
}