'use strict';

var MongoConnection     = require('./../../../database/providers/mongodb/MongoConnection');
const healthCheckConstants     = require('../../../../shared/constants/HealthCheckConstants');

exports.check =  (options) => {
  return new Promise( async (resolve, reject) => {
    const dsName = options.connectionName;
    try {
      let db = await getDatabase(dsName);

      db.stats().then((stats) => {
        if (stats.ok === 1) {
          resolve(healthCheckConstants.OK);
        } else {
          reject(new Error("Could not connect to mongodb server."));
        }
      }).catch(err => {
        reject(err);
      });

    } catch (error) {
      reject(error);
    }
  });
};


function getDatabase(dsName){
  return new Promise(function(resolve, reject){

    let mongodb;
    try{
      mongodb = MongoConnection.getDatabase(dsName);
    }catch(err){

    }

    if (!mongodb){
      MongoConnection.initialise(dsName).then(function () {
        mongodb = MongoConnection.getDatabase(dsName);
        resolve(mongodb);
      },function errorFunc(err) {
        reject(err);
      });
    }
    else{
      resolve(mongodb);
    }
  });
}

